【发布时间】:2020-07-26 19:29:17
【问题描述】:
我有从正确答案here复制的下一个代码:
public static String decrypt(String cipherText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] cipherData = Base64.getDecoder().decode(cipherText);
byte[] saltData = Arrays.copyOfRange(cipherData, 8, 16);
MessageDigest md5 = MessageDigest.getInstance("MD5");
final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, saltData, secret.getBytes(StandardCharsets.UTF_8), md5);
SecretKeySpec key = new SecretKeySpec(keyAndIV[0], "AES");
IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);
byte[] encrypted = Arrays.copyOfRange(cipherData, 16, cipherData.length);
Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decryptedData = aesCBC.doFinal(encrypted);
String decryptedText = new String(decryptedData, StandardCharsets.UTF_8);
return decryptedText;
}
如何在 Java 中为此编写加密函数?我试过这样的东西,但它不起作用:
public static String encrypt(String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, getNextSalt(), secret.getBytes(StandardCharsets.UTF_8), md5);
SecretKeySpec skeySpec = new SecretKeySpec(keyAndIV[0], "AES");
IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static byte[] getNextSalt() {
byte[] salt = new byte[8];
RANDOM.nextBytes(salt);
return salt;
}
【问题讨论】:
-
encrypt必须返回OpenSSL格式的数据,即前8个字节是Salted__的ASCII编码,然后是8个字节的salt,然后是实际的密文,全部是Base64连接后编码。盐是随机生成的。据我所知,您的encrypt-method 缺少到这种 OpenSSL 格式的转换。顺便说一句,OpenSSL 格式是不安全的,不是标准的,here。 -
你能用代码写下你的答案吗?我会给你正确的答案。谢谢。
标签: java encryption aes salt cryptojs