Created
May 30, 2014 07:10
-
-
Save interchen/941f4a5b8ba468c47423 to your computer and use it in GitHub Desktop.
Java AES ECB NoPadding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 加密 | |
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