我使用以下代码加密数据
final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(),
"AES");
final String myIV = "89ABCDEF01234567";
Cipher c = null;
try {
try {
c = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(
myIV.getBytes()));
byte[] encrypted = c.doFinal(msgfromEB.getBytes(),0,msgfromEB.getBytes().length);
我像这样解密
c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(
myIV.getBytes()));
byte[] decryptedBytes = c.doFinal(encrypted ,0,encrypted .length);
System.out.println("decrypted string is"+new String(decryptedBytes));
它正在工作,我能够正确加密和解密
但是如果我正在转换成这样的字符串
String myString = new String (encrypted);
并再次获得这样的字节数组
byte[] newbytearray = myString.getBytes();
现在我正在尝试解密
c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(
myIV.getBytes()));
byte[] decryptedBytes = c.doFinal(newbytearray ,0,newbytearray .length);
System.out.println("decrypted string is"+new String(decryptedBytes));
现在我得到一个错误
javax.crypto.IllegalBlockSizeException:最后一个块在解密中不完整
如果我使用 base64 转换它工作正常,但我不想这样做,因为它增加了长度。有没有其他的选择来解决这个问题?