Android加密和解密错误-javax.crypto.IllegalBlockSizeException:解密中的最后一个块不完整 [英] Android Encryption and Decryption Error - javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
问题描述
以下代码中的解密问题.我有一个加密的字符串被发送到setData().我正在尝试解密加密的字符串(数据).我不断收到的错误是
I have an issue with the decryption in the following code. I have a encrypted string being sent to setData(). I am trying to decrypt the encrypted string(data). The error I keep getting is
javax.crypto.IllegalBlockSizeException:解密中的最后一个块不完整
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
byte[] data;
String key = "tkg96827pco74510";
byte[] encryptedOut;
String decryptedOut;
Key aesKey;
Cipher cipher;
public void setData(String dataIn){
this.data = dataIn.getBytes();
try {
aesKey = new SecretKeySpec(key.getBytes(), "AES");
cipher = Cipher.getInstance("AES");
}catch(Exception e){
System.out.println("SET DATA ERROR - " + e);
}
}
public void encrypt() {
try{
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
encryptedOut = cipher.doFinal(data);
}catch(Exception e){
System.out.println(e);
}
}
public void decrypt(){
try {
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decryptedOut = new String(cipher.doFinal(data));
}catch(Exception e){
System.out.println("Decrypt Error: " + e);
}
}
public byte[] getEncrypted() {
return encryptedOut;
}
public String getDecrypted(){
return decryptedOut;
}
推荐答案
问题是由以下行引起的:
The problem is caused by this line :
decryptedOut = new String(cipher.doFinal(data));
在这里,您正在传递原始数据以进行解密.但是您应该在此处传递 encryptedOut
.
Here you are passing original data to decrypt. But you should pass encryptedOut
here.
因此解决方案是:
decryptedOut = new String(cipher.doFinal(encryptedOut));
是的,请通过某种编码机制将String转换为byteArray,反之亦然,例如"UTF-8"
.
and yes, Please pass some encoding mechanism to convert String to byteArray and vice-versa like "UTF-8"
.
所以正确的行应该是:
decryptedOut = new String(cipher.doFinal(encryptedOut),"UTF-8");
鉴于您已经完成了到这样的字节的转换:
Given you have done conversion to bytes like this :
this.data = dataIn.getBytes("UTF-8");
这篇关于Android加密和解密错误-javax.crypto.IllegalBlockSizeException:解密中的最后一个块不完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!