IllegalBlockSizeException试图进行加密和解密的字符串使用AES时 [英] IllegalBlockSizeException when trying to encrypt and decrypt a string with AES

查看:5824
本文介绍了IllegalBlockSizeException试图进行加密和解密的字符串使用AES时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与我想要一个字符串,并将其存储在共享preferences 之前加密硬盘codeD密钥。这是code我到目前为止有:

I have a hardcoded key with which I want to encrypt a string before storing it in SharedPreferences. This is the code I have so far:

public class TokenEncryptor {

    private final static String TOKEN_KEY = "91a29fa7w46d8x41";

    public static String encrypt(String plain) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
            SecretKeySpec newKey = new SecretKeySpec(TOKEN_KEY.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
            return new String(cipher.doFinal(plain.getBytes()));
        } catch (Exception e) {
            Ln.e(e);
            return null;
        }
    }

    public static String decrypt(String encoded) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
            SecretKeySpec newKey = new SecretKeySpec(TOKEN_KEY.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
            return new String(cipher.doFinal(encoded.getBytes()));
        } catch (Exception e) {
            Ln.e(e);
            return null;
        }
    }
}

这似乎在解密方法结束时捕获异常:

It seems to be catching an exception at the end of decrypt method:

javax.crypto.IllegalBlockSizeException:错误:0606506D:数字信封套路:EVP_DecryptFinal_ex:错误的最终块长度

有人点我在正确的方向?我有一种感觉,我做错了什么实例化 IvParameterSpec

Can someone point me in the right direction? I have a feeling I'm doing something wrong instantiating IvParameterSpec.

推荐答案

在加密字符串AES,你会得到一个字节数组回来。尝试这些字节直接转换为一个字符串会导致各种各样的问题。如果需要输出的加密方法是一个字符串,然后用的Base64 ,而不是试图直接转换。在您的解密方法,转换的Base64 字符串回一个字节数组解密的字节数组之前。

When you encrypt a string with AES, you get an array of bytes back. Trying to convert those bytes directly to a string will cause all sorts of problems. If you require the output from your encryption method to be a string, then use Base64 rather than attempting a direct conversion. In your decryption method, convert the Base64 string back into a byte array before decrypting the byte array.

此外,不要使用的GetBytes()由于输出取决于系统默认值。使用的GetBytes(UTF-8)或什么的。消除歧义。

Also, do not use getBytes() since the output depends on the system defaults. Use getBytes("utf-8") or whatever. That eliminates ambiguity.

这篇关于IllegalBlockSizeException试图进行加密和解密的字符串使用AES时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆