1

这是我的解码类,它使用 Bouncycastle,Rijndael 256 解密。我有一个错误:

mode.doFinal(decoded, bytesProcessed);

堆栈跟踪:

org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
    at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(Unknown Source)
    at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(Unknown Source)
    at com.imocom.cryptography.Decoder.decrypt(Decoder.java:71)
    at TestingLauncher.main(TestingLauncher.java:46)

这是进行编码的php代码:

<?php 
    $string = "This is a sample string.";
    $secret = "1234567890987654321234567898765";

    $result = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,
                                            $secret,
                                            $string,
                                            MCRYPT_MODE_CBC,
                                            "1234567890123455555555555555555"
                                           ));

    echo $result."\n";

    $back = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,
                          $secret,
                          base64_decode($result),
                          MCRYPT_MODE_CBC,
                          "12345678999999999999999999999999");

    echo $back."\n";
    ?>

这是电话:

byte[] decoded;
decoded = decoder.decrypt(Base64.decodeBase64(encodedTextFromServer));

谁能帮助我,为什么会这样?

public class Decoder {

byte[] IV = null;
byte[] encryptionKey = null;
Cipher cipher;
SecretKeySpec key;
BlockCipher blockCipher;
ParametersWithIV _param;

PaddedBufferedBlockCipher mode;
int blockSize;

public Decoder() {

    Security.addProvider(new BouncyCastleProvider());

    try {

        IV = "1234543333333333333333333333333".getBytes("UTF-8");
        encryptionKey = "12222222222222222222222222222222".getBytes("UTF-8");

        blockCipher = new CBCBlockCipher(new RijndaelEngine(256));
        _param = new ParametersWithIV(new KeyParameter(encryptionKey), IV);
        mode = new PaddedBufferedBlockCipher(blockCipher);
        blockSize = blockCipher.getBlockSize();

    } catch (Exception e) {

    }

}

public byte[] decrypt(byte[] encodedText) {

    byte[] decoded = new byte[mode.getOutputSize(encodedText.length)];

    try {
        mode.init(false, _param);


        int bytesProcessed = mode.processBytes(encodedText, 0, encodedText.length, decoded, 0);

        mode.doFinal(decoded, bytesProcessed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return decoded;
}
4

2 回答 2

3

PaddedBufferedBlockCipher来自Bouncy Castle中构造函数的 JavaDoc :

创建缓冲分组密码 PKCS7 填充

然而 PHP 默认不使用良好的填充模式,而是简单地添加零值字节,直到到达块的末尾。ZeroBytePadding这在充气城堡中被称为。

所以请使用ZeroBytePadding,或者更好,在 PHP 中实现 PKCS#7 填充。

于 2013-07-09T14:30:45.740 回答
-1

我建议您尝试将字符串视为十六进制而不是 UTF-8。例如,您的 IV 是“81a577a68f9e94d6cc02fe23b6ee64a4”。那是 16 字节的十六进制或 32 字节的 UTF-8。AES IV 应该是 16 字节以匹配块大小。我可以看到其他错误,但我将把这些留给您查找,因为您说这是针对课程的。

于 2013-07-09T11:43:49.060 回答