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