我正在使用带有 AES 的 Java Cryptography API 来加密用于用户识别 cookie 的短文本字符串。
据我了解,与密钥的大小相比,某些加密算法在与少量文本一起使用时并不安全。为了确保我不会让我的数据不安全,我需要知道什么?我是否需要确保要加密的字符串比密钥长?还有其他地雷吗?
要生成密钥,我使用encryptionType = "AES"
and执行以下操作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");
}