AES/CFB模式需要使用与原始数据长度相等的IV向量进行初始化。在加密和解密过程中,必须使用相同的IV向量,否则加密和解密会失败。此外,对于CFB模式,使用nopadding选项,在加密之前应确保原始数据长度恰好是块大小的倍数。
以下是示例代码:
加密:
String plaintext = "hello world";
String algorithm = "AES";
String transformation = "AES/CFB/NoPadding";
SecretKey secretKey = new SecretKeySpec("0123456789abcdef".getBytes(), algorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
解密:
String algorithm = "AES";
String transformation = "AES/CFB/NoPadding";
SecretKey secretKey = new SecretKeySpec("0123456789abcdef".getBytes(), algorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] plaintext = cipher.doFinal(ciphertext);