Android Encryption and Decryption Error - javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

≡放荡痞女 提交于 2020-02-20 06:18:17

问题


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: 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;
}

回答1:


The problem is caused by this line :

decryptedOut = new String(cipher.doFinal(data));

Here you are passing original data to decrypt. But you should pass encryptedOut here.

So the solution would be :

decryptedOut = new String(cipher.doFinal(encryptedOut));

and yes, Please pass some encoding mechanism to convert String to byteArray and vice-versa like "UTF-8".

So the correct line would be :

decryptedOut = new String(cipher.doFinal(encryptedOut),"UTF-8");

Given you have done conversion to bytes like this :

this.data = dataIn.getBytes("UTF-8");



回答2:


The problem is here:

public String getDecrypted()

and here:

decryptedOut = new String(cipher.doFinal(data));

String is not a container for binary data. You need to encode the cipher text somehow before you put it into a String. For example, base64-encoding.



来源:https://stackoverflow.com/questions/30098239/android-encryption-and-decryption-error-javax-crypto-illegalblocksizeexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!