【发布时间】:2012-11-10 22:38:33
【问题描述】:
我尝试使用 salt 来解密 AES 加密消息,但它总是返回 null 值。谁能看看我哪里做错了?
public static String decryptMessage(String encryptedMessage, String salt) {
String decryptedMessage = null;
String valueToDecrypt = encryptedMessage;
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
for (int i = 0; i < ITERATIONS; i++) {
byte[] decodedValue = Base64.decodeBase64(valueToDecrypt);
byte[] decVal = c.doFinal(decodedValue);
decryptedMessage = new String(decVal).substring(salt.length());
valueToDecrypt = decryptedMessage;
}
} catch (Exception e) {
e.printStackTrace();
}
return decryptedMessage;
}
**EDIT:**
这是我认为有效的相应加密方法。
private static final String ALGORITHM = "AES";
private static final int ITERATIONS = 5;
private static final byte[] keyValue = new byte[] { '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6' };
public static String encryptMessage(String message, String salt) {
String encMessage = null;
byte[] encVal = null;
String messageWithSalt = null;
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
for (int i = 0; i < ITERATIONS; i++) {
messageWithSalt = salt + encMessage;
encVal = c.doFinal(messageWithSalt.getBytes());
byte[] encryptedValue = new Base64().encode(encVal);
encMessage = new String(encryptedValue);
}
} catch (Exception e) {
e.printStackTrace();
}
return encMessage;
}
PS:迭代不是 0;
【问题讨论】:
-
您忘记发布相应的加密代码了。
-
@Leigh 好吧,有了
catch语句,您可以假设它也会在任何解密错误时返回 null :) 说真的,每一行都至少有一个错误,可能除了 @ 987654326@ 方法,我想当我们知道ALGORITHM的值时我们就会知道。
标签: java cryptography aes salt