I just want to encrypt a string submitted through a form before saving
it to the DB. And then decrypt it again when I need to retrieve and
use it.

Im trying to use the OpenSSL::Cipher library. I have the following
module for encryption/decryption
[code]
require 'openssl'

module AESCrypt
  # Decrypts a block of data (encrypted_data) given an encryption key
  # and an initialization vector (iv).  Keys, iv's, and the data
  # returned are all binary strings.  Cipher_type should be
  # "AES-256-CBC", "AES-256-ECB", or any of the cipher types
  # supported by OpenSSL.  Pass nil for the iv if the encryption type
  # doesn't use iv's (like ECB).
  #:return: => String
  #:arg: encrypted_data => String
  #:arg: key => String
  #:arg: iv => String
  #:arg: cipher_type => String
  def AESCrypt.decrypt(encrypted_data, key, iv, cipher_type="aes-256-
cbc")
    aes = OpenSSL::Cipher::Cipher.new(cipher_type)
    aes.decrypt
    aes.key = key
    aes.iv = iv if iv != nil
    aes.update(encrypted_data) + aes.final
  end

  # Encrypts a block of data given an encryption key and an
  # initialization vector (iv).  Keys, iv's, and the data returned
  # are all binary strings.  Cipher_type should be "AES-256-CBC",
  # "AES-256-ECB", or any of the cipher types supported by OpenSSL.
  # Pass nil for the iv if the encryption type doesn't use iv's (like
  # ECB).
  #:return: => String
  #:arg: data => String
  #:arg: key => String
  #:arg: iv => String
  #:arg: cipher_type => String
  def AESCrypt.encrypt(data, key, iv, cipher_type="aes-256-cbc")
    aes = OpenSSL::Cipher::Cipher.new(cipher_type)
    aes.encrypt
    aes.key = key
    aes.iv = iv if iv != nil
    aes.update(data) + aes.final
  end
end
[/code]
And here is the model code where I encrypt and decrypt the string.
[code]
  def encrypt_cc_pass
    return if cc_pass.blank?
    self.cc_pass_key = Time.now.to_s
    self.cc_pass_iv = Date.today.to_s
    self.encrypted_cc_pass = AESCrypt.encrypt(cc_pass, cc_pass_key,
cc_pass_iv)
  end

  def decrypted_cc_pass
    AESCrypt.decrypt(encrypted_cc_pass, cc_pass_key, cc_pass_iv)
  end
[/code]

And this is the error I get

wrong final block length in:config/initializers/aes_crypt.rb:20:in
`final'

Anyone know what im doing wrong here?
Also, Im not able to understand the inners of encryption here. Is
there any gem with good documentation or simpler usage?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to