-
-
Save simoleone/ed458f4404db46896a08aff4591761cd to your computer and use it in GitHub Desktop.
AlertUpload: Client-Side Encryption v1 (ruby)
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 'base64' | |
require 'json' | |
require 'openssl' | |
def wrap_session_key(public_key_pem, key) | |
rsa_pkey = OpenSSL::PKey::RSA.new(public_key_pem) | |
rsa_pkey.public_encrypt(key, OpenSSL::PKey::RSA::PKCS1_PADDING) | |
end | |
def encrypt(public_key_pem, plaintext) | |
cipher = OpenSSL::Cipher.new('aes-256-gcm') | |
cipher.encrypt | |
session_key = cipher.random_key # 256 bit randomly generated key | |
iv = cipher.random_iv # 12 byte randomly generated IV | |
ciphertext = cipher.update(plaintext) + cipher.final | |
auth_tag = cipher.auth_tag | |
header = JSON.dump( | |
{ | |
version: 1, | |
key_id: 'hb-123', | |
encrypted_session_key: Base64.strict_encode64(wrap_session_key(public_key_pem, session_key)), | |
iv: Base64.strict_encode64(iv), | |
auth_tag: Base64.strict_encode64(auth_tag) | |
} | |
) | |
buf = StringIO.new | |
buf.binmode | |
buf << header | |
buf << "\x00" | |
buf << ciphertext | |
buf.string | |
end | |
encrypt(public_key, 'attack at dawn') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment