Skip to content

Instantly share code, notes, and snippets.

@vcsjones
Created February 22, 2022 15:46
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 vcsjones/21af2365e2ec48cb7ccc7499e4481c7f to your computer and use it in GitHub Desktop.
Save vcsjones/21af2365e2ec48cb7ccc7499e4481c7f to your computer and use it in GitHub Desktop.
require 'openssl'
def encrypt(plaintext)
key = "\1" * 16
nonce = "\2" * 12
aes = OpenSSL::Cipher.new('aes-128-gcm')
aes.encrypt
aes.key = key
aes.iv = nonce
aes.auth_data = ''
ciphertext = aes.update(plaintext) + aes.final
tag = aes.auth_tag
return [ciphertext, tag]
end
def xor_strings(str1, str2)
min = str1.bytesize < str2.bytesize ? str1.bytesize : str2.bytesize
bytes1 = str1.byteslice(0...min)
bytes2 = str2.byteslice(0...min)
bytes1.bytes.zip(bytes2.bytes).map { _1 ^ _2 }.pack('c*')
end
# Encrypt
plaintext1 = 'hello world!'
plaintext2 = 'i am sleepy!'
ciphertext1, authtag1 = encrypt(plaintext1)
ciphertext2, authtag2 = encrypt(plaintext2)
# "Decrypt" ciphertext1 knowing only the contents of plaintext2 and
# ciphertext2.
puts xor_strings(ciphertext1, xor_strings(plaintext2, ciphertext2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment