4

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.

user664833
  • 18,397
  • 19
  • 91
  • 140

1 Answers1

4

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
rahulmishra
  • 620
  • 1
  • 13
  • 29
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • Thanks for your answer. I have changed the cipher as you suggested, and the decryption *seems* to have been successful, though I cannot actually confirm that yet, as I am now having issues with inflating the decrypted data (maybe issues between `C#` and `Ruby` re: `Zlib` deflating and inflating). Anyway, regarding Ruby's default padding, I found [an SO answer saying that PKCS5 is the default](http://stackoverflow.com/a/12611287/664833). The [documentation](http://www.ruby-doc.org/stdlib-1.9.2/libdoc/openssl/rdoc/OpenSSL/Cipher.html) is mute about this detail (or at least I haven't found it). – user664833 Nov 06 '12 at 19:43
  • 1
    The Wiki article on padding says "PKCS5 padding is the same as PKCS7, except that technically it can only be used to pad 64 bit blocks. In practice the two are used interchangeably." (http://en.wikipedia.org/wiki/Padding_(cryptography)) So AES cannot use PKCS5 padding by definition, because the block size is fixed to 128 (>64) – Patrick Oscity Nov 07 '12 at 10:50
  • 3
    Still it will be helpful for some people(like me) if this answer is updated to include how to specify padding and other parameters in ruby. Thankyou for your answer – Zia Ul Rehman Mughal Jan 23 '17 at 09:08