例程:EVP_DecryptFinal_ex:android中的最终块长度错误

Dav*_*kro 5 android aes

实际上我在一个应用程序中工作,并解决AES的问题

我在这一行有一个错误 byte[] results = cipher.doFinal(Base64.encode(text.getBytes("UTF-8"), Base64.DEFAULT));

错误:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

String key = "grnR++15jgNFVmVg61UvQA==";
String data = "vrvwe+9wVhyNJmb/KcLD2K2j9gqkwVFXq0jt0qL7zyHHG2JWpkvr+VpG/QHm6INW01WsBZcpRYYk25bMtjWgLY6dzFNs3WLXZRMnVtIDhjuIfv0sp2RKvhjNLEu3Gscz4sdxYYS6XcLOWAY705Ll48+mA55Ke5WSq71jVR+TCJVT0w2nYZvzviE+N0QwRX5EZjCMjbaH4gpFLr+LsNevkAQ7e7Id4oSvrwqJ3PyUS4mo8OvPcUjKDhQCJc39k2aqBBaZ9O1AuqQqCOWpgy2XW9kacAP8zrcDRO7oNtSbIM0sqIyKS4PGzXiL+hw43hs33d/VO8tvLGHWOE0UvWkQY0QPJqzRDmmWpRTgr0Xt56UxIXjjAmteVlb+TWo3kzRSUQ2Un+ScCfEBHjaNJNShE27zSeXOjkMWpB0jobSMJy6KdR/fqopHmYcWd41DNOz25nkUtQBmBK+x5sqM0dLswL8TKfb7MdIdhqdZaHt7h1CTNpozEwg+A7ZEkcGZ3hcGAwPWkPrg1yoXE5uaeCzdslf4knbXBxIx8ekrBiyUY5BhMPak/7LJm9D64RPQEpdOUTeg2fh9nKShXnr1OdKGrf68H7c/rSincB2uqgEuo9oHaBIIwm0RuUkM/jCjeLmVEE2zIjJE2osk2XQKf4iOlHP12XQOCtITYBZm8jc0OKmjpelFaWNLFheAE/txRk/NSS+qmUcWor1BSXDZAxje0ftwTl0jYz69U3tW9pDm3yooWWU51ORoTpQHqEGLumQyJom3OfsSkQ/T/pEMxY6B3a7TmJ+8u+QJla+ZCHFav5aKL1Ojy7xijYzIlsoVP9m7nDp30oVA8rpI8vYKpUHXUuQPxdVV4/yjvCeRkWT/veQtHpA9OWYDSTQLdRYfOOeQoxg/kGua4HU0RlC8IVgm/iJJnpWJgvdKD0KKmVgwFKmZ1TFg5yMRN4oOPDk4yhtnjPV9VhJU4lHztHw7TG53UWblwieeorD+v94LHySXFAj1tyd4tebgrvFqyuPovT4iP7Xm37KA/LmtrCPiCaBn6g==;

        try {
            Decrypt(data,key);
        } catch (Exception e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

方法

String Decrypt(String text, String key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] keyBytes = Base64.decode(key.getBytes(), Base64.DEFAULT);
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    byte[] b = new byte[keySpec.getEncoded().length];
    System.arraycopy(keySpec.getEncoded(), 0, b, 0, b.length);
    IvParameterSpec ivSpec = new IvParameterSpec(b);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] results = cipher.doFinal(Base64.encode(text.getBytes("UTF-8"), Base64.DEFAULT));
    String  decoded = new String(cipher.doFinal(results), "UTF-8");
    return decoded;
}
Run Code Online (Sandbox Code Playgroud)

Che*_*amp 3

我重新开始了解你的解密例程如何工作。看看下面的例子。我对您将在代码中看到的key和字段做了一些假设。data了解这些字段的来源及其格式非常重要。该代码已经过测试并且可以作为演示。

这些评论应该可以帮助您完成。

至于您看到的错误,它表明您的加密字符串的长度不正确。因为它似乎被填充,所以它应该是 16 字节的倍数(事实并非如此),这是 AES 块大小。您给出的字符串缺少终止引号,因此无论如何它都无法编译。很难说加密字符串究竟发生了什么。

初始化向量未正确设置。iv 独立于密钥,在加密期间单独导出,并且在解密期间“给出”。看看下面的例程中初始化向量是如何设置的。

我希望这有帮助。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final String SECRET_KEY = "PloasdlOoasdllasiewjsaroo9o55ooo"; // 256 bits
        // encryptedString is encrypted form of the string "This is just some test data." It has
        // the initialization vector added as a prefix.
        final String encryptedString = "yDdtrKCl30b+fndIMkhasDhBNk+OGYqiM6uVVF89pu2WSnjMsz1lnw6x4H23QWxP";
        String decryptedString;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            decryptedString = doDecryption(encryptedString, SECRET_KEY);
        } catch (Exception e) {
            decryptedString = "Error doing decryption!";
            e.printStackTrace();
        }
        Log.d(TAG, ">>Decrypted string=" + decryptedString);
    }

    /**
     * Decrypt from Base 64 representation of a string with initialization vector prefix.
     *
     * @param sourceBase64 Initialization vector prefixed to string to decrypt in base 64.
     * @param secretKey    The secret key used to do the encryption and the decryption.
     * @return The decrypted string.
     * @throws Exception Exception
     */

    String doDecryption(String sourceBase64, String secretKey) throws Exception {
        Cipher cipher;                  // The cipher used to encrypt and decrypt
        int cipherBlockSize;            // Size of the cipher block
        byte[] sourceBytes;             // Decoded byte array from sourceBase64
        byte[] iv;                      // Initialization vector
        byte[] bytesToDecrypt;          // Bytes on which to perform decryption

        // String passed in is in base 64. Translate so we can work with it.
        sourceBytes = Base64.decode(sourceBase64.getBytes("UTF-8"), Base64.DEFAULT);

        // Get the secretKey spec for our secret key to work with our cipher.
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");

        // Set up the cipher.
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipherBlockSize = cipher.getBlockSize();

        // The initialization vector prefixes the string that was passed in (sourceBase64).
        // The length of this initialization vector is the same as our cipher's blocksize.
        iv = new byte[cipherBlockSize];

        // Split the inititializatoin vector from the bytes we need to decrypt.
        bytesToDecrypt = new byte[sourceBytes.length - cipherBlockSize];
        System.arraycopy(sourceBytes, 0, iv, 0, iv.length);
        System.arraycopy(sourceBytes, iv.length, bytesToDecrypt, 0, bytesToDecrypt.length);

        // Now do the actual decryption.
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
        return new String(cipher.doFinal(bytesToDecrypt));
    }

    private static final String TAG = "MainActivity";
}
Run Code Online (Sandbox Code Playgroud)