Question

I am starting with the following C# encryption code, and want to decrypt with Ruby. My problem is that I don't know how to set the padding mode in Ruby/OpenSSL. I specifically need to use PKCS7.

C# encryption

System.Security.Cryptography.Aes c = new System.Security.Cryptography.AesManaged();
c.Mode = CipherMode.CBC;
c.Padding = PaddingMode.PKCS7;   # <-- how to set this in Ruby world?
c.KeySize = 256;
c.BlockSize = 128;
c.Key = key;
c.IV = iv;
...

Ruby decryption

d = OpenSSL::Cipher.new('AES-128-CBC') # oops, this should have been AES-256-CBC
d.decrypt
d.key = key
d.iv  = iv
...

I am currently using Ruby 1.9.2, but can use whatever version necessary.

Was it helpful?

Solution

The constructor parameter actually reads <name>-<key length>-<mode>, so first of all, you probably want to use AES-256-CBC in order to use a 256 Bit key. [source]

The AES Block size is fixed to 128 Bit anyway, so you do not need to adjust this parameter. [source]

Also, it seems that Ruby uses PKCS7 Padding by default, so there's no need to adjust this, either. [source]

Therefore, you should be good to go with just

c = OpenSSL::Cipher.new('AES-256-CBC')
c.decrypt
c.key = key
c.iv = iv
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top