81,092
社区成员
发帖
与我相关
我的任务
分享
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;
}
}
encrypt = new String(encryptAES(key.getBytes("UTF-8"), text.getBytes("UTF-8"))); //问题出在此处,由于加密后的字节数组不一定满足UTF-8格式导致信息丢失
System.out.println((text.equals(new String(decryptAES(key.getBytes("UTF-8"), encryptAES(key.getBytes("UTF-8"), text.getBytes("UTF-8"))), "UTF-8")))); //你写的加解密代码是正确的
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
public class MainClass {
public static void main(String[] args) throws Exception {
SecureRandom random = new SecureRandom("1234567890123456".getBytes());
byte[] ivBytes = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128, random);
Key key = generator.generateKey();
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
String input = "trefferwrsfsd";
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] cipherText = cipher.doFinal(input.getBytes());
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] plainText = cipher.doFinal(cipherText);
System.out.println("plain : " + new String(plainText));
}
}
我试的没问题。你参考下把