AES Cipher Encryption & Decryption Algorithms Using Ruby On Rails

AES Encryption & Decryption Algorithms using Ruby On Rails
AES Encryption & Decryption Algorithms using Ruby On Rails

Encryption and decryption methods using ruby on rails for secure data transfer , using AES Cipher logic.

There are several ways to create a Cipher instance. Generally, a Cipher algorithm is categorized by its name, the key length in bits and the cipher mode to be used. The most generic way to create a Cipher is the following.

cipher = OpenSSL::Cipher.new(‘<name>-<key length>-<mode>’)

There are various cipher modes CBC, CFB, OFB and CTR.
I using 128 bit key size. There are 128, 256 bit key sizes also.

For each algorithm supported, there is a class defined under the Cipher class that goes by the name of the cipher, e.g. to obtain an instance of AES, you could also use like:-

1) cipher = OpenSSL::Cipher.new(‘AES-128-CBC’)
2) cipher = OpenSSL::Cipher.new(‘AES-128-ECB’)

I have used Base64​ schemes for Encoding & Decoding the data

KEY:- Is the secret text which is used as key by cipher
ALGORITHM:- Is the cipher mode with the key bit size(like 128,256)

Base64​ schemes for Encoding & Decoding the data i have made use for security.

U can save the below code in the .rb file and use it.

require ‘openssl’
require ‘base64’

class AesEncryptDecrypt

KEY = “***************************************”
ALGORITHM = ‘AES-128-ECB’

def self.encryption(msg)
begin
cipher = OpenSSL::Cipher.new(ALGORITHM)
cipher.encrypt()
cipher.key = KEY
crypt = cipher.update(msg) + cipher.final()
crypt_string = (Base64.encode64(crypt))
return crypt_string
rescue Exception => exc
puts (“Message for the encryption log file for message #{msg} = #{exc.message}”)
end
end
def self.decryption(msg)
begin
cipher = OpenSSL::Cipher.new(ALGORITHM)
cipher.decrypt()
cipher.key = KEY
tempkey = Base64.decode64(msg)
crypt = cipher.update(tempkey)
crypt << cipher.final()
return crypt
rescue Exception => exc
puts (“Message for the decryption log file for message #{msg} = #{exc.message}”)
end
end

end

Example:-

I have used KEY and ALGORITHM as mentioned below for example:-

KEY = “EncryptDecryptGurudathBN”
ALGORITHM = ‘AES-128-ECB’

Encryption:-
irb(main):007:0> AesEncryptDecrypt.encryption(‘gurudath’)
=> “rUPKObydUJd9cY9agm3Glw==\n”

Decryption:-
irb(main):008:0> AesEncryptDecrypt.decryption(‘rUPKObydUJd9cY9agm3Glw==’)
=> “gurudath”

We will update with more information with upcoming days.

Regards
Gurudath BN

Advertisements

5 Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s