我使用AES加密Java加密API來加密用於識別用戶識別Cookie的短文本字符串。JCA和AES應該注意哪些安全性地雷?
我的理解是,與密鑰的大小相比,某些加密算法在使用少量文本時不安全。爲了確保我不會讓我的數據不安全,我需要知道什麼?我需要確保要加密的字符串比密鑰長嗎?還有其他的地雷嗎?
生成密鑰我做與encryptionType = "AES"
和keySize = 128
如下:
public SecretKey createKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance(encryptionType);
keyGen.init(keySize); // 192 and 256 bits may not be available
return keyGen.generateKey();
}
public String encrypt(Key key, String str) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
Cipher ecipher = Cipher.getInstance(encryptionType);
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new BASE64Encoder().encode(enc);
}
public String decrypt(Key key, String str) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
Cipher dcipher = Cipher.getInstance(encryptionType);
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] dec = new BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
由於缺乏MAC而導致的填充字符是一個常見的嚴重問題。 – CodesInChaos 2014-06-11 10:23:59
您應該明確指定一個模式,而不是隻指定「AES」。 – CodesInChaos 2014-06-11 10:25:16