-
-
Save vcsjones/21af2365e2ec48cb7ccc7499e4481c7f 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' | |
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