BlockSize must be 128 in this implementation

3.2k views Asked by At

I'm using the following code to decrypt some strings I reicive but I'm getting the following error: BlockSize must be 128 in this implementation.

I would like to know if there is any way and how it would be possible to decrypt the strings I get without decreasing the size since I can't change my key and IV because the strings were encrypted with then.

       private string Decrypt(string text)
       {
           var inputByteArray = Convert.FromBase64String(text);

           var rm = new RijndaelManaged();
           rm.BlockSize = 256;
           rm.IV = Encoding.UTF8.GetBytes("11111111111111111111111111111111");
           rm.KeySize = 256;
           rm.Key = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes("11111111-1111-1111-1111-111111111111"));

           var decryptor = rm.CreateDecryptor();
           var msDecrypt = new MemoryStream(inputByteArray);
           var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
           var srDecrypt = new StreamReader(csDecrypt);
           return srDecrypt.ReadToEnd();
       }

I'm using .netcore 5

1

There are 1 answers

0
leafar29 On BEST ANSWER

to solve this problem i followed Topaco suggestion and used the BouncyCastle/C# library and that solved the error i was getting, below I leave the solution I used based on other forums.

public static string Decrypt(string cipherText)
        {
    var ivStringBytes = Encoding.UTF8.GetBytes("11111111111111111111111111111111");
            var cipherTextBytes = Convert.FromBase64String(cipherText);
            var keyBytes = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes("11111111-1111-1111-1111-111111111111"));
            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 finalBytes = cipher.DoFinal(cipherTextBytes);
            var final = Encoding.UTF8.GetString(finalBytes);
            return final;
}

And this is the package that i used:

<PackageReference Include="BouncyCastle.NetCore" Version="1.8.10" />