Skip to content

Instantly share code, notes, and snippets.

@joeljunstrom
Last active May 23, 2020 12:36
Show Gist options
  • Save joeljunstrom/0791f8687df375979f0c6a69d57a1e4d to your computer and use it in GitHub Desktop.
Save joeljunstrom/0791f8687df375979f0c6a69d57a1e4d to your computer and use it in GitHub Desktop.
class User < ApplicationRecord
attribute :otp_secret, :encrypted
end
class EncryptedType < ActiveRecord::Type::Value
class << self
memoize def secret_key
Rails.application.key_generator.generate_key("encrypted_type")
end
end
def type
:string
end
def cast(value)
value.to_s.presence
end
def deserialize(value)
crypter.decrypt(value) if value.present?
end
def serialize(value)
crypter.encrypt(value) if value.present?
end
memoize def crypter
Crypter.new(secret_key)
end
end
# frozen_string_literal: true
require "rbnacl"
class Crypter
attr_reader :secret_key
def initialize(secret_key)
@secret_key = secret_key
end
def encrypt(value)
Base64.strict_encode64(engine.encrypt(value))
end
def decrypt(cipher)
engine.decrypt(Base64.strict_decode64(cipher))
end
private
memoize def engine
RbNaCl::SimpleBox.from_secret_key(
RbNaCl::Hash.sha256(secret_key)
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment