Skip to content

Instantly share code, notes, and snippets.

@angelortiz-dev
Created October 19, 2018 21:24
Show Gist options
  • Select an option

  • Save angelortiz-dev/77be01891ac93fba2625ce39535e241a to your computer and use it in GitHub Desktop.

Select an option

Save angelortiz-dev/77be01891ac93fba2625ce39535e241a to your computer and use it in GitHub Desktop.
Simply encrypt and decrypt Strings in Ruby.
#
# Got from: https://gist.github.com/wteuber/5318013
require 'openssl'
def encrypt(plain_text, key)
cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt
cipher.key = Digest::SHA1.hexdigest key
s = cipher.update(plain_text) + cipher.final
s.unpack('H*')[0].upcase
end
def decrypt(cipher_text, key)
cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt
cipher.key = Digest::SHA1.hexdigest key
s = [cipher_text].pack("H*").unpack("C*").pack("c*")
cipher.update(s) + cipher.final
end
puts plain = 'confidential' # confidential
puts key = 'secret' # secret
puts cipher = encrypt(plain, key) # 5C6D4C5FAFFCF09F271E01C5A132BE89
puts decrypt(cipher, 'guess') # raises OpenSSL::Cipher::CipherError
puts decrypt(cipher, key) # confidential
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment