Skip to content

Instantly share code, notes, and snippets.

@interchen
Created May 30, 2014 07:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save interchen/941f4a5b8ba468c47423 to your computer and use it in GitHub Desktop.
Save interchen/941f4a5b8ba468c47423 to your computer and use it in GitHub Desktop.
Java AES ECB NoPadding
// 加密
public static byte[] ecbEncrypt(byte sSrc[], String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16倍数
if (sKey.length() % 16 != 0) {
System.out.print("Key长度不是16倍数");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc);
return encrypted;
}
// 解密
public static byte[] ecbDecrypt(byte sSrc[], String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16倍数
if (sKey.length()%16 != 0) {
System.out.print("Key长度不是16倍数");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
try {
return cipher.doFinal(sSrc);
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment