解析javax.crypto.IllegalBlockSizeException:解密时最后一个块不完整

时间:2013-09-05 09:55:14

标签: javascript android encryption

我使用以下代码解密消息

try {
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ips = new IvParameterSpec(iv);

            // 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, getSecretKeySpec(), 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 "";

这是我的getSecretKeySpec()

public static Key getSecretKeySpec() {

        if (SECRET_KEY == null) {
            byte[] keyBytes = new byte[16];

            // byte[] bytes = Globals.APPLICATION.APP_KEY.getBytes();
            byte[] bytes = Globals.context.getPackageName().getBytes();
            if (bytes.length > 16) {
                int j = 0;
                for (int i = bytes.length - 1; i >= 0; i--) {
                    keyBytes[j] = bytes[i];
                    j++;
                    if (j > 7)
                        break;
                }
            } else {
                for (int i = 0; i < 16; i++)
                    keyBytes[i] = 'q';

                int j = 0;
                for (int i = bytes.length - 1; i >= 0; i--) {
                    keyBytes[j] = bytes[i];
                }
            }

            SECRET_KEY = new SecretKeySpec(keyBytes, "AES");
        }
        return SECRET_KEY;
    }

我在SO和其他人中搜索了很多但是却无法解决这个问题。任何人都可以指出我的错误。

1 个答案:

答案 0 :(得分:0)

试试这种方式

替换此

byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

WITH

 byte[] iv = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0','0' };