Last active
March 11, 2021 22:48
-
-
Save jqr/1f5ddf18981f5b9c7d443d52e2edbf1a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class SomeModel < ApplicationRecord | |
serialize :client_secret, EncryptedStringSerializer.new | |
serialize :credentials, EncryptedJsonSerializer.new | |
end |
This file contains hidden or 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
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 |
This file contains hidden or 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
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 |
This file contains hidden or 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 "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