我正在尝试在 Java 中跨两个设备实现 AES 加密的基本示例。然而,每次我们运行应用程序时,在两台设备上使用相同的密码(128 位)生成 AES 密钥会导致两台设备上的密钥不同。所以我们无法解密我们在设备之间发送的文本。
我使用的方法如下,它们是我在其他地方找到的代码的稍微修改版本:
public String encryptMessage(String message, String password) throws Exception {
// Creating key and cipher
SecretKeySpec aesKey = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
byte[] iv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
//AES cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivspec);
byte[] encrypted;
encrypted = cipher.doFinal(message.getBytes());
return new String(encrypted, "UTF-8");
}
public String decryptMessage(String encryptedMessage, String password) throws Exception {
// Creating key and cipher
byte[] passwordBytes = password.getBytes("UTF-8");
SecretKeySpec aesKey = new SecretKeySpec(passwordBytes, "AES");
byte[] iv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
//AES cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
// decrypting the text
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivspec);
String decrypted = new String(cipher.doFinal(encryptedMessage.getBytes(Charset.forName("UTF-8"))));
//returning decrypted text
return decrypted;
}
每次运行这段代码,打印出aesKey,都不一样。
我对 AES 和对称加密的理解是,给定相同的密码,它应该生成相同的密钥,否则它如何能够解密人工制品?我是否弄错了 AES 棒的一端,或者有人可以建议可能会发生什么?
Helenr
相关分类