C# 如何修复';Org.BouncyCastle.Crypto.InvalidCipherTextException:';垫块损坏'';在Rijndael解密中

C# 如何修复';Org.BouncyCastle.Crypto.InvalidCipherTextException:';垫块损坏'';在Rijndael解密中,c#,encryption,bouncycastle,rijndael,C#,Encryption,Bouncycastle,Rijndael,我也有同样的情况 所以我修正了那个帖子的代码,并替换了我的旧代码 public static string Decrypt(string cipherText, string superSecretPassPhrase) { if (cipherText == null) { throw new ArgumentNullException(nameof(cipherText)); } // Get the complete stream of by

我也有同样的情况

所以我修正了那个帖子的代码,并替换了我的旧代码

public static string Decrypt(string cipherText, string superSecretPassPhrase)
{
    if (cipherText == null)
    {
        throw new ArgumentNullException(nameof(cipherText));
    }
    // Get the complete stream of bytes that represent:
    // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
    var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
    // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
    var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
    // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
    var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
    // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
    var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

    using (var password = new Rfc2898DeriveBytes(superSecretPassPhrase, saltStringBytes, _iterations))
    {
        var keyBytes = password.GetBytes(Keysize / 8);
        using (var symmetricKey = new RijndaelManaged())
        {
            symmetricKey.BlockSize = 256;
            symmetricKey.Mode = CipherMode.CBC;
            symmetricKey.Padding = PaddingMode.PKCS7;
            using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
            {
                using (var memoryStream = new System.IO.MemoryStream(cipherTextBytes))
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        var plainTextBytes = new byte[cipherTextBytes.Length];
                        var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memoryStream.Close();
                        cryptoStream.Close();
                        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                    }
                }
            }
        }
    }
}
按新准则

public static string Decrypt(string cipherText, string superSecretPassPhrase)
{
    if (cipherText == null)
    {
        throw new ArgumentNullException(nameof(cipherText));
    }
    // Get the complete stream of bytes that represent:
    // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
    var cipherTextBytesWithSaltAndIv =  Convert.FromBase64String(cipherText);
    // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
    var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
    // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
    var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
    // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
    var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

    using (var password = new Rfc2898DeriveBytes(superSecretPassPhrase, saltStringBytes, _iterations))
    {
        var keyBytes = password.GetBytes(Keysize / 8);
        var engine = new RijndaelEngine(256);
        var blockCipher = new CbcBlockCipher(engine);
        var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
        var keyParam = new KeyParameter(keyBytes);
        var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);
        cipher.Init(false, keyParamWithIV);
        var outputBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)];
        var length = cipher.ProcessBytes(cipherTextBytes, outputBytes, 0);
        var finalBytes = cipher.DoFinal(outputBytes, 0, length);  //Exception HERE!!!
        var final = Encoding.UTF8.GetString(finalBytes);
        return final;
    }
}
我面临的问题是,我的一些案例(我不确定,但似乎很长的
密文
会导致:
'pad block corrupted'异常

比如说

static void Main(string[] args)
{
    var superSecretPassPhrase = "Office";
    var input = @"U3/7njQjVmcahG9/PtK9fhivCU1l128UACKeBvo6d+T5XwTx+A3qxkfKZCObhaMsOJQDkLrLpAUXCw6txSRrmh5vd4iYfAfTSHzrgdtlvff0gtKfwpmzYAXdvk8tJFiFnvM7xWQlxlmybNtTYVpk1c1UCvNOcyPR2YuooxJ3FV1otIzyRLMSBEOtasV0uyCnoe79mkh54/2XrGXCsLDGpQ==";
    var result = OldStringDecryptor.Decrypt(input,superSecretPassPhrase); /*everything is ok as I expected "DjSRsJ8i7RJEdZ8ooMH9RH1p2oBV7G1zPJg6hdceULIXzF9LhHJYeAb5MCOK9D9M"*/
    var result2=
        NewBouncyCastleDecryptor.Decrypt(input,superSecretPassPhrase);//throws pad block corrupted Exception
}

在新代码中还需要更改什么?

您在
Decrypt
方法中使用了错误的
DoFinal
重写(检查参数名称)。此外,

替换此项:

var outputBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)];
var length = cipher.ProcessBytes(cipherTextBytes, outputBytes, 0);
var finalBytes = cipher.DoFinal(outputBytes, 0, length);
与:


我有同样的问题,但是PaddedBufferedBlockCipher类没有一个只有一个参数的DoFinal方法。所以我不明白这个解决方案是如何工作的,除非你使用另一个你没有提到的密码实现…我和最初的提问者有完全相同的错误。并且尝试了他的和你的解决方案,我仍然在完全相同的行中得到相同的错误:Org.BouncyCastle.Crypto.InvalidCipherTextException:“pad block corrupted”@ruben450在使用错误密钥解密(或者在这个问题中,误用了API)的简单情况下,基本错误消息是你所期望的。
var finalBytes = cipher.DoFinal(cipherTextBytes);