-
-
Save asonge/4f035a38a9b31339d8f5 to your computer and use it in GitHub Desktop.
OpenSSL Errors with AES-256-GCM
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
defmodule Parser do | |
@key "go generate a 32 byte random key" | |
@algorithm :aes_gcm | |
@auth_data "" | |
# Strings generated by this fuction fail to be decrypted unless one of the hardcoded IV values is used. | |
def encrypt(bin_data) when is_binary(bin_data) do | |
# These two hardcoded values where generated by: OpenSSL::Random.random_bytes(12) | |
# iv = <<133, 29, 202, 53, 242, 73, 247, 202, 244, 58, 243, 238>> | |
# iv = <<134, 240, 63, 15, 40, 68, 240, 242, 108, 27, 226, 144>> | |
# iv = :crypto.rand_bytes(12) | |
iv = :crypto.strong_rand_bytes(12) | |
{cipher_text, cipher_tag} = :crypto.block_encrypt(@algorithm, @key, iv, {@auth_data, bin_data}) | |
iv <> cipher_tag <> cipher_text | |
end | |
# This function will return an error if the :crypto.strong_rand_bytes was used to generate the IV. | |
def decrypt(<<iv::binary-size(12),cipher_tag::binary-size(16),cipher_text::binary>>) do | |
:crypto.block_decrypt(@algorithm, @key, iv, {@auth_data, cipher_text, cipher_tag}) | |
end | |
end | |
Parser.decrypt Parser.encrypt("Hello, world!") |
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' | |
class Parser | |
def initialize | |
@key = 'go generate a 32 byte random key' | |
@algorithm = 'aes-256-gcm' | |
@auth_data = '' | |
end | |
def decrypt(bin_data) | |
decipher = OpenSSL::Cipher.new(@algorithm).decrypt | |
decipher.key = @key | |
decipher.iv = bin_data[0..11] | |
decipher.auth_tag = bin_data[12..27] | |
decipher.auth_data = @auth_data | |
decipher.update(bin_data[28..-1]) + decipher.final | |
end | |
def encrypt(bin_data) | |
cipher = OpenSSL::Cipher.new(@algorithm).encrypt | |
cipher.key = @key | |
iv = cipher.random_iv # Calls OpenSSL::Random.random_bytes(12) to set IV internally | |
cipher.auth_data = @auth_data | |
cipher_text = cipher.update(bin_data) + cipher.final | |
[iv, cipher.auth_tag, cipher_text].join | |
end | |
end | |
Parser.new.decrypt Parser.new.encrypt("Hello, world!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment