Skip to content

Instantly share code, notes, and snippets.

@jqr
Last active March 11, 2021 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqr/1f5ddf18981f5b9c7d443d52e2edbf1a to your computer and use it in GitHub Desktop.
Save jqr/1f5ddf18981f5b9c7d443d52e2edbf1a to your computer and use it in GitHub Desktop.
class SomeModel < ApplicationRecord
serialize :client_secret, EncryptedStringSerializer.new
serialize :credentials, EncryptedJsonSerializer.new
end
class EncryptedStringSerializer
KEY = if Rails.env.test?
SecureRandom.bytes(32)
else
Base64.decode64(Rails.application.credentials.identity[:storage_key_base64])
end
def load(serialized_value)
encryptor.decrypt_and_verify(serialized_value, purpose: :storage) if serialized_value.present?
end
def dump(string)
encryptor.encrypt_and_sign(string, purpose: :storage)
end
def encryptor
@encyrptor ||= ActiveSupport::MessageEncryptor.new(KEY)
end
end
class EncryptedJsonSerializer
KEY = if Rails.env.test?
SecureRandom.bytes(32)
else
Base64.decode64(Rails.application.credentials.identity[:storage_key_base64])
end
def load(serialized_value)
encryptor.decrypt_and_verify(serialized_value, purpose: :storage) if serialized_value.present?
end
def dump(json)
encryptor.encrypt_and_sign(json, purpose: :storage)
end
def encryptor
@encyrptor ||= ActiveSupport::MessageEncryptor.new(KEY, serializer: MessagePackDeflater)
end
end
require "msgpack"
class MessagePackDeflater
def self.dump(v)
Zlib::Deflate.deflate(MessagePack.dump(v))
end
def self.load(v)
MessagePack.load(Zlib::Inflate.inflate(v))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment