3

I have the same sittuation Decrypt Rijndael 256 Block Size with BouncyCastle

So I've fixed code from that post, and replaced my old code

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);
                    }
                }
            }
        }
    }
}

by new code

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;
    }
}

I faced with isssue that some my cases (I'am not sure but seems like long cipherText leads to : 'pad block corrupted' Exception).

For instance

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
}

what else do I need to change in the new code?

CSDev
  • 3,177
  • 6
  • 19
  • 37

1 Answers1

6

You are using the wrong override of DoFinal in your Decrypt method (examine the argument names). Also, the

Replace this:

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

with:

var finalBytes = cipher.DoFinal(cipherTextBytes);
Peter Dettman
  • 3,867
  • 20
  • 34
  • 1
    I have the same issue but the class PaddedBufferedBlockCipher does not have a DoFinal method with only one parameter. So I don't understand how can this solution work unless you use another cipher implementation that you do not mention... – Migs Nov 20 '19 at 14:14
  • I have the exact same error as the initial questioner. and tryed both his and your solution i still get the same error at the exact same line: Org.BouncyCastle.Crypto.InvalidCipherTextException: 'pad block corrupted' – ruben450 Jun 01 '21 at 14:24
  • 1
    @ruben450 That basic error message is something you expect anyway in the straightforward case that you have decrypted with the wrong key (or as in this question, misused the API). – Peter Dettman Jun 06 '21 at 05:15