Search code examples
.netvb.netcryptographybouncycastlerijndael

How to use PKCS7 with BouncyCastle Rijndael in .Net


I'm working on a project that requires me to cipher some data using Rijndael, CBC and PKCS7...

I have some examples that show me the initial data and the result I should get after applying Rijndael... I tried using .Net RijndaelManaged class but got nothing similar to the expected value and I believe it's because of some issue while converting my Byte array to String...

On the other hand, using BouncyCastle's Rijndael implementation I managed to get something very similar to the expected value, and the difference is that I can't set the PKCS7 padding mode... and my biggest issue is that I cannot find documentation anywhere!

Here's a very simplified version of my Encrypt function, notice I included my key and IV definitions here just for testing.

Public Shared Function Encrypt(data As Byte()) As Byte()
    Dim theCipher As New Org.BouncyCastle.Crypto.Engines.RijndaelEngine()
    Dim ciphr As New PaddedBufferedBlockCipher(New CbcBlockCipher(theCipher), new Pkcs7Padding())

    Dim key As New KeyParameter(System.Text.Encoding.UTF8.GetBytes("---exampleKey---"))
    Dim iv As Byte() = System.Text.Encoding.UTF8.GetBytes("---example-IV---")

    Dim IVKey As New ParametersWithIV(key, iv)
    ciphr.Init(True, IVKey)

    Dim size As Integer = ciphr.GetOutputSize(data.Length)
    Dim result(size) As Byte

    Dim oLen As Integer = ciphr.ProcessBytes(data, 0, data.Length, result, 0)
    oLen += ciphr.DoFinal(result, oLen)

    If oLen < size Then
        Dim tmp(oLen) As Byte
        Array.Copy(result, 0, tmp, 0, oLen)
        result = tmp
    End If

    Return result
End Function

Solution

  • Basically your plain text is exactly N times the blocksize. This means that a full block of padding is added before encryption, resulting in an additional block of ciphertext. Furthermore, because the way VB creates arrays, you need to use Dim varName(size - 1) as Byte.