Protect sensitive data using 128 bit encryption
There comes a time, every developer need to protect sensitive information stored in database such as debit/credit card infomation(although I wouldn’t recommend to store such data) or other sensitive information of that level. That means we need to store those informations in such a way that its not readable directly(encrypted) and must be able to get the information back when needed. We can achieve this using ezcrypto gem. EzCrypto is an easy to use wrapper around the OpenSSL ruby library and uses AES 128 bit encryption algorithm. So lets see how can we use it in our ruby applicaiton.
First of all we need to require the gem
require 'ezcrypto'
Ezcrypto gem uses a key to encrypt the data and the key can be generated using a password and a salt. Then we use the key’s encrypt method to encrypt our sensitive data.
key = EzCrypto::Key.with_password('password', 'system salt')
encrypted_text = key.encrypt('This is the text we want to encrypt')
encrypted_text is the text we will be saving in database.
Now to decypher what has been encrypted and saved in the database, we need the same key which has been used for encryption else it will throw OpenSSL::Cipher::CipherError exception
key = EzCrypto::Key.with_password('password', 'system salt')
decrypted_text = key.decrypt(encrypted_text)
Best way to generate the key is to either get password from user himself while decryption or to use the user login password itself. We can store the system salt in our ruby application itself. This way we can make sure that the only user is able to decrypt the sensitive information.
Sample example is given below:
require 'ezcrypto'
begin
key = EzCrypto::Key.with_password('password', 'some system salt')
encrypted_text = key.encrypt('This is my secret text')
# key generated second time to decrypt the secret text
key = EzCrypto::Key.with_password('password', 'some system salt')
decrypted_text = key.decrypt(encrypted_text)
puts "The decrypted text is: #{decrypted_text}"
rescue OpenSSL::Cipher::CipherError
puts "Error while decrypting"
end
#=> The decrypted text is: This is my secret text
If the key was generated with wrong password say “password1” and the key is used for decrypting the encrypted_text, the output would be
#=> Error while decrypting