Skip to content

Instantly share code, notes, and snippets.

@pat
Last active September 18, 2019 06:27
Show Gist options
  • Save pat/1fb950fac3642252be5de4747801db6b to your computer and use it in GitHub Desktop.
Save pat/1fb950fac3642252be5de4747801db6b to your computer and use it in GitHub Desktop.
require "openssl"
require "digest/sha2"
require "base64"
require "ostruct"
# Just like Aws::KMS::Client, this responds to decrypt and encrypt,
# using the same parameters and output objects (well, at least for
# the purposes of what I've used it for).
#
# So, you can inject this class in instead for test environments
# where you might not want to be talking to AWS.
#
# This code isn't trying to provide amazingly super-high-strength
# encryption, it's just trying to respond similarly so the data
# that gets passed around in testing is reasonably similar to
# production. Also: any encrypted values can only be decrypted
# within the current process, because the symmetric key and vector
# are regenerated when the class is loaded by Ruby.
#
class Client
ALGORITHM = "AES-256-CBC"
VECTOR = OpenSSL::Cipher.new(ALGORITHM).random_iv
KEY = begin
digest = Digest::SHA256.new
digest.update "symmetric key"
digest.digest
end
def decrypt(payload)
OpenStruct.new plaintext: switch(:decrypt, payload[:ciphertext_blob])
end
def encrypt(payload)
OpenStruct.new ciphertext_blob: switch(:encrypt, payload[:plaintext])
end
private
def switch(mode, input)
cipher = OpenSSL::Cipher.new(ALGORITHM)
cipher.public_send mode
cipher.key = KEY
cipher.iv = VECTOR
cipher.update(input) + cipher.final
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment