我使用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