Skip to content

Instantly share code, notes, and snippets.

@eveevans
Forked from wteuber/encrypt_decrypt.rb
Created July 22, 2017 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eveevans/9833359b42d1f8ed9c4286c6e7fe0762 to your computer and use it in GitHub Desktop.
Save eveevans/9833359b42d1f8ed9c4286c6e7fe0762 to your computer and use it in GitHub Desktop.
Simply encrypt and decrypt Strings in ruby.
require 'openssl'
class String
def encrypt(key)
cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC').encrypt
cipher.key = Digest::SHA1.hexdigest key
s = cipher.update(self) + cipher.final
s.unpack('H*')[0].upcase
end
def decrypt(key)
cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC').decrypt
cipher.key = Digest::SHA1.hexdigest key
s = [self].pack("H*").unpack("C*").pack("c*")
cipher.update(s) + cipher.final
end
end
puts plain = 'confidential' # confidential
puts key = 'secret' # secret
puts cipher = plain.encrypt(key) # 5C6D4C5FAFFCF09F271E01C5A132BE89
puts cipher.decrypt('guess') # raises OpenSSL::Cipher::CipherError
puts cipher.decrypt(key) # confidential
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment