Skip to content

Instantly share code, notes, and snippets.

@mguezuraga
Created December 29, 2016 12:36
Show Gist options
  • Save mguezuraga/a65af1ab372561298437bfb0ba44bdfc to your computer and use it in GitHub Desktop.
Save mguezuraga/a65af1ab372561298437bfb0ba44bdfc to your computer and use it in GitHub Desktop.
require 'openssl'
require 'digest/sha1'
require 'base64'
@cipher = OpenSSL::Cipher.new('aes-256-cbc')
def encrypt(data, key)
@cipher.encrypt
@cipher.key = key
rc = @cipher.update(data)
rc << @cipher.final
return rc
end
def decrypt(data, key)
@cipher.decrypt
@cipher.key = key
rc = @cipher.update(Base64::decode64(data))
rc << @cipher.final
return rc
end
key_40bytes = Digest::SHA1.hexdigest('ac4feb33d990c4b6ab1dbc8fb533cdecbffd443b')
key_32bytes = Digest::SHA1.hexdigest('ac4feb33d990c4b6ab1dbc8fb533cdecbffd443b')[0,32]
key = key_32bytes
secret = "super secret text"
secret_encripted_32 = Base64::encode64(encrypt(secret, key)).strip.delete("\n")
secret_decripted = decrypt(secret_encripted_32, key)
puts "Key used: #{key}"
puts "Encrypted text (base64): #{secret_encripted_32}"
puts "Decrypted text: #{secret_decripted}"
puts "Key used: #{key}"
puts "Key length: #{key.bytesize}"
puts "----"
key = key_40bytes
secret = "super secret text"
secret_encripted_40 = Base64::encode64(encrypt(secret, key)).strip.delete("\n")
secret_decripted = decrypt(secret_encripted_40, key)
puts "Key used: #{key}"
puts "Encrypted text (base64): #{secret_encripted_40}"
puts "Decrypted text: #{secret_decripted}"
puts "Key used: #{key}"
puts "Key length: #{key.bytesize}"
puts "Secrets match!" if secret_encripted_32 == secret_encripted_40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment