How to code Ruby equivalent of PHP’s mcrypt_encrypt() function
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
$key ~ 16 Bytes (AES-128)
cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
$key ~ 24 Bytes (AES-192)
cipher = OpenSSL::Cipher::Cipher.new("aes-192-cbc")
$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
精彩评论