Last active
December 4, 2017 15:34
-
-
Save masciugo/f2da780fa6404fdcedef221ba862bb1a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
KEY = '1'*32 | |
IV = '1'*12 | |
ALG = 'aes-256-gcm' | |
def bin2hex(s) | |
s.unpack('H*').first | |
end | |
def hex2bin(s) | |
s.scan(/../).map { |x| x.hex }.pack('c*') | |
end | |
def encrypt(plaintext) | |
cipher = OpenSSL::Cipher.new(ALG) | |
cipher.encrypt | |
cipher.key = KEY | |
cipher.iv = IV | |
ciphertext = cipher.update(plaintext) | |
bin2hex(ciphertext) | |
end | |
def decrypt(ciphertext) | |
decipher = OpenSSL::Cipher.new(ALG) | |
decipher.decrypt | |
decipher.key = KEY | |
decipher.iv = IV | |
plaintext = decipher.update(hex2bin(ciphertext)) | |
end | |
puts encrypt "00000001" # => 4666a782147f1450 | |
puts encrypt "00000002" # => 4666a782147f1453 | |
puts encrypt "00000003" # => 4666a782147f1452 | |
puts decrypt encrypt "00000001" # => 00000001 | |
puts decrypt encrypt "00000002" # => 00000002 | |
puts decrypt encrypt "00000003" # => 00000003 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment