开发者

How to code Ruby equivalent of PHP’s mcrypt_encrypt() function

开发者 https://www.devze.com 2023-01-04 05:55 出处:网络
If I write the following code mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $raw, MC开发者_JAVA技巧RYPT_MODE_CBC, $iv);

If I write the following code

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $raw, MC开发者_JAVA技巧RYPT_MODE_CBC, $iv);

How to write in ruby?


Here is Ruby equivalent using OpenSSL,

  cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv
  encrypted = cipher.update(raw)
  encrypted << cipher.final


You can use the openssl library for this. I think what you need is here for symmetric key encryption:

http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/


Can ezcrypto help? Default it uses standard aes-128-cbc but does know other algorithms.


MCRYPT_RIJNDAEL_128 denotes the blocksize 16 Bytes and 3 key sizes are possible

  1. $key ~ 16 Bytes (AES-128)

    cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")

  2. $key ~ 24 Bytes (AES-192)

    cipher = OpenSSL::Cipher::Cipher.new("aes-192-cbc")

  3. $key ~ 32 Bytes (AES-256)

    cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")

And then we can use the following code to perform encryption

cipher.encrypt
cipher.key = key
cipher.iv = iv
encrypted = cipher.update(raw)
encrypted << cipher.final
0

精彩评论

暂无评论...
验证码 换一张
取 消