简体   繁体   中英

How to set Padding Mode with Ruby/OpenSSL decryption / encryption?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM