import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES1 {
public static byte[] encryptAES(byte key[], byte data[]) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
return cipher.doFinal(data);
}
public static byte[] decryptAES(byte key[], byte msg[]) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
return cipher.doFinal(msg);
}
public static void main(String[] args) {
String key = "1234567890123456";
String text = "1234567890";
String encrypt = "";
String decrypt = "";
try {
encrypt = new String(encryptAES(key.getBytes("UTF-8"), text.getBytes("UTF-8")));
System.out.println("encrypt : " + byte2hex(encrypt.getBytes("UTF-8")));
decrypt = new String(decryptAES(key.getBytes("UTF-8"), encrypt.getBytes("UTF-8")));
System.out.println("decrypt : " + decrypt);
System.out.println("text.equals(decrypt): " + text.equals(decrypt));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String byte2hex(byte[] b) {
String a = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
a = a + hex;
}
return a;
}
}
代码如上,使用的是 AES 的 CTR 无填充加密算法,但是解密后所得串与原串不相等。