J2ME AES解密错误(org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted)

5

我正在使用Bouncy Castle进行AES算法的加密和解密。

我的加密和解密可以正常工作,但是当明文长度较大时会出现错误。

有时甚至会出现未解密的数据。

public static boolean setEncryptionKey(String keyText)
{
    byte[] keyBytes = keyText.getBytes();

    key = new KeyParameter(keyBytes);
    engine = new AESFastEngine();
    cipher = new PaddedBufferedBlockCipher(engine);

    return true;
}

加密:

public static String encryptString(String plainText)
{

        byte[] plainArray = plainText.getBytes();

        cipher.init(true, key);
        byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)];
        int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0);
        cipher.doFinal(cipherBytes, cipherLength);
        String cipherString = new String(cipherBytes);
        return cipherString;
    }

解密:

public static String decryptString(String encryptedText)
{

        byte[] cipherBytes = encryptedText.getBytes();
        cipher.init(false, key);
        byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
        int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
        cipher.doFinal(decryptedBytes, decryptedLength);
        String decryptedString = new String(decryptedBytes);

        int index = decryptedString.indexOf("\u0000");
        if (index >= 0)
        {
            decryptedString = decryptedString.substring(0, index);
        }
        return decryptedString;
    }

这个解密过程出现了以下错误。
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
        at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(+30)
        at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(+190)
        at com.NewCrypto.decryptString(NewCrypto.java:103)
        at com.New_Midlet.startApp(New_Midlet.java:23)
        at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:44)
        at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:375)
        at com.sun.midp.main.Main.runLocalClass(Main.java:477)
        at com.sun.midp.main.Main.main(+80)

可能存在什么问题?
1个回答

2

这条线

String cipherString = new String(cipherBytes);

出现了一个问题。 cipherBytes 是一个具有任意值的字节数组,无法使用任何Java字符串解码器将其转换为字符串。您应该只发送/保存密文作为字节数组。如果必须将其转换为字符串,则必须使用编码器。通常使用Base64编码器和Base16(十六进制)编码器。您可以使用Apache Commons Codec或我最喜欢的Harder Base64 codec


任何仍然输出字节而不是字符的base64编码器在我看来都有点愚蠢。我已经可以想象当有人尝试将其流式传输到UTF-16 XML文件时会出现多么可怕的情况。此外,它似乎不支持除默认形式以外的任何其他base64形式。嗯,也许我应该把我的编码器也提供出来。 - Maarten Bodewes
@owlstead:我同意。Harder编解码器将输出字符串并支持愚蠢的Apache commons风格。 - President James K. Polk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接