javax.crypto.IllegalBlockSizeException: last block incomplete in decryption - Decrypting an encrypted AES String

前端 未结 3 1390
一个人的身影
一个人的身影 2020-12-29 08:42

I am trying to decrypt the string \"~9?8?m???=?T?G\" that I receive from a back-end server which uses OpenSSL to encrypt the String using AES-256-CBC. There is

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 09:03

    So thanks to @owlstead, I was able to figure out the solution. It was that I made the mistake of Base64encoding an already Base64 encoded string. The following is by code chunk.

    public static String decryptText(String textToDecrypt) {
        try {
            byte[] decodedValue = Base64.decodeBase64(textToDecrypt.getBytes());
    
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ips = new IvParameterSpec(iv);
    
            byte[] input = textToDecrypt.getBytes();
    
            Cipher cipher = Cipher.getInstance(ENCRYPTION_METHOD);
    
            // decryption pass
            cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY, ips);
            byte[] plainText = cipher.doFinal(decodedValue);
    
            return new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Decipher error for " + textToDecrypt, e);
        }
    
        return "";
    }
    

    The corresponding encrypting is like this

    public static String encryptText(String textToEncrypt) {
        try {
            byte[] guid = "1234567890123456".getBytes("UTF-8");
    
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ips = new IvParameterSpec(iv);
    
            // The secret key from the server needs to be converted to byte array for encryption.
            byte[] secret = ENCRYPTION_SECRET_HASH.getBytes("UTF-8");
    
            // we generate a AES SecretKeySpec object which contains the secret key.
            // SecretKeySpec secretKey = new SecretKeySpec(secret, "AES");
            Cipher cipher = Cipher.getInstance(ENCRYPTION_METHOD);
            cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY, ips);
    
            byte[] cipherText = cipher.doFinal(textToEncrypt.getBytes());
            byte[] base64encodedSecretData = Base64.encodeBase64(cipherText);
            String secretString = new String(base64encodedSecretData);
            return secretString;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Encryption error for " + textToEncrypt, e);
        }
        return "";
    }
    

提交回复
热议问题