【问题标题】:J2ME AES Decryption Error(org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted)J2ME AES 解密错误(org.bouncycastle.crypto.InvalidCipherTextException:垫块损坏)
【发布时间】:2011-05-18 11:02:43
【问题描述】:

我正在使用带有充气城堡的 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)

可能是什么问题?

【问题讨论】:

    标签: java-me aes encryption bouncycastle midlet


    【解决方案1】:

    线

    String cipherString = new String(cipherBytes);
    

    是一个错误。 cipherBytes 是具有任意值的字节数组,不能使用任何 Java 字符串解码器转换为字符串。您应该将密码发送/保存为字节数组。如果必须将其设为字符串,则必须使用编码器。 Base64 编码器经常被使用,Base16(十六进制)也是如此。您可以使用Apache Commons Codec 或我最喜欢的Harder Base64 codec

    【讨论】:

    • 在我看来,任何仍然输出字节而不是字符的 base64 编码器都有些愚蠢。当有人试图将其流式传输到 UTF-16 XML 文件时,我已经看到了恐怖。此外,它似乎不支持任何其他形式的 base64,而不是默认形式。嗯,也许我也应该提供我的编码器。
    • @owlstead:我同意。 Harder 编解码器将输出字符串并支持愚蠢的 Apache commons 样式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多