通常,您不需要为具有确定性行为的算法生成随机数的东西。此外,当您使用 ECB 块模式时,您不需要 IV,这是 Java 的默认设置。准确地说,Java 默认为"AES/ECB/PKCS5Padding"
for in Cipher.getInstance("AES")
。
所以你应该可以接受这样的代码:
// lets use the actual key value instead of the platform specific character decoding
byte[] secret = Hex.decodeHex("25d6c7fe35b9979a161f2136cd13b0ff".toCharArray());
// that's fine
SecretKeySpec secretKey = new SecretKeySpec(secret, "AES");
// SecureRandom should either be slow or be implemented in hardware
SecureRandom random = new SecureRandom();
// first create the cipher
Cipher eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// filled with 00h characters first, use Cipher instance so you can switch algorithms
byte[] realIV = new byte[eCipher.getBlockSize()];
// actually fill with random
random.nextBytes(realIV);
// MISSING: create IvParameterSpec
IvParameterSpec ivSpec = new IvParameterSpec(realIV);
// create the cipher using the IV
eCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
// NOTE: you should really not encrypt passwords for verification
String stringToEncrypt = "mypassword";
// convert to bytes first, but don't use the platform encoding
byte[] dataToEncrypt = stringToEncrypt.getBytes(Charset.forName("UTF-8"));
// actually do the encryption using the data
byte[] encryptedData = eCipher.doFinal(dataToEncrypt);
现在看起来好多了。我使用 Apache commons 编解码器来解码十六进制字符串。
请注意,您需要使用 保存realIV
,encryptedData
并且您没有包含完整性保护,例如 MAC(对于密码,您可能不需要它)。