Skip to content

Instantly share code, notes, and snippets.

@cheald
Last active December 10, 2015 21:38
Show Gist options
  • Save cheald/4496816 to your computer and use it in GitHub Desktop.
Save cheald/4496816 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
class Cryptor
def initialize
@secret = "fd5d148867091d7595c388ac0dc50bb465052b764c4db8b4b4c3448b52ee0b33df16975830acca82"
@cipher = OpenSSL::Cipher.new("AES-256-CFB")
end
def encrypt(*numbers)
@cipher.encrypt
@cipher.random_iv
@cipher.key = @secret
data = numbers.pack("Q*")
encrypted = @cipher.update(data) + @cipher.final
digest = OpenSSL::Digest::Digest.new('SHA1')
signed = encrypted + OpenSSL::HMAC.digest(digest, @secret, encrypted)
Base64.urlsafe_encode64(signed)
end
def decrypt(data)
unencoded = Base64.urlsafe_decode64(data)
encrypted = unencoded.slice!(0..(unencoded.length - 21))
signature = unencoded
digest = OpenSSL::Digest::Digest.new('SHA1')
raise "Bad signature" unless signature == OpenSSL::HMAC.digest(digest, @secret, encrypted)
@cipher.decrypt
@cipher.key = @secret
(@cipher.update(encrypted) + @cipher.final).unpack("Q*")
end
end
cryptor = Cryptor.new
encrypted = cryptor.encrypt(9223372036854775800, 9223372036854775800)
puts "Encrypted is %d bytes" % encrypted.length
puts encrypted
puts cryptor.decrypt(encrypted).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment