decryption · encryption · Ruby · Testing

Ruby — Encryption and Decryption using OpenSSL

Code:

require 'rubygems'
require 'openssl'

$key = "A75435F0B240012A9489000C2952E41F"

class String

def encrypt(key=$key)
e = OpenSSL::Cipher::Cipher.new 'DES-EDE3-CBC'
e.encrypt key
s = e.update self
s << e.final
s = s.unpack('H*')[0].upcase
s
end

def decrypt(key=$key)
e = OpenSSL::Cipher::Cipher.new 'DES-EDE3-CBC'
e.decrypt key
s = self.to_a.pack("H*").unpack("C*").pack("c*")
s = e.update s
s << e.final
end
end
puts "raveendran".encrypt("password")
puts "509067DC2076497134DBF9A7DE5992B2".decrypt("password")

Output

509067DC2076497134DBF9A7DE5992B2

raveendran

Note:

You can chnage the $key vlaue.

You can encrypt the string with password. The password should match when trying to decrypt the encrypted string.

Advertisements

One thought on “Ruby — Encryption and Decryption using OpenSSL

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