我需要爲每次運行AES(在JAVA中)生成不同的令牌,因爲我所做的是我附加了使用當前系統時間加密的字符串,使用java中的System.currentTimeMillis()
並將兩者分開他們使用管道字符「|」。但是,我們面臨的問題是,每次運行時加密的字符串都是相同的,並且解密時我得到正確的字符串。爲什麼會這樣呢?使用AES加密的令牌不會改變
代碼加密:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESEncryptor {
private static final String ALGO = "AES";
private final static byte[] keyValue =new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't','S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
byte[] encryptedValue = Base64.encodeBase64(encVal);
String encryptedPass = new String (encryptedValue);
return encryptedPass;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
Base64.decodeBase64(encryptedData);
byte[] decordedValue = Base64.decodeBase64(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
1st run :
argument passed to encrypt : somepassword|1364311519852
encrypted string : 5pQ1kIC+8d81AD7zbLOZA==(encrypted string)
decrypted string : somepassword|1364311519852
2nd run :
argument passed to encrypt : somepassword|1364311695048
encrypted string : 5pQ1kIC+8d81AD7zbLOZA==(same encrypted string as before)
decrypted string : somepassword|1364311695048
誰能幫爲什麼會發生這樣的嗎?
你的密文是從「somestring | 1364300620387」加密的簡稱,也不能解密回它。如果我們假設你的模式不使用填充,即使Base64應該比原始字節長至少1.25倍。不可能。 – jbtule 2013-03-26 12:52:41
我在上面提到的密文是虛擬的,實際的是24個字符。我給出了一個虛擬的例子,以舉例說明我面臨的情況。 – 2013-03-26 13:38:51
是的,當你有目的地給出錯誤的信息,沒有人可以幫助你。 – jbtule 2013-03-26 13:58:21