2019-09-13 13:19:54 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-09-13 13:43:26 -04:00
|
|
|
class AsymmetricKey < ApplicationRecord
|
2019-09-13 15:50:52 -04:00
|
|
|
PRIVATE_KEY_CLEAR_DELAY = 1.hour.freeze
|
2019-09-13 17:43:08 -04:00
|
|
|
|
|
|
|
attr_accessor :private_key_pem, :private_key_pem_secret
|
|
|
|
|
|
|
|
################
|
|
|
|
# Associations #
|
|
|
|
################
|
|
|
|
|
|
|
|
belongs_to :account, optional: true
|
|
|
|
|
|
|
|
###############
|
|
|
|
# Validations #
|
|
|
|
###############
|
|
|
|
|
|
|
|
validates :public_key_pem,
|
|
|
|
presence: true,
|
|
|
|
uniqueness: true
|
|
|
|
|
|
|
|
validates :public_key_der,
|
|
|
|
presence: true,
|
|
|
|
uniqueness: true
|
|
|
|
|
|
|
|
validates :has_password, exclusion: { in: [nil] }
|
|
|
|
|
|
|
|
validates :bits,
|
2019-09-13 18:26:03 -04:00
|
|
|
allow_nil: true,
|
2019-09-13 17:43:08 -04:00
|
|
|
numericality: {
|
|
|
|
only_integer: true,
|
|
|
|
greater_than: 0,
|
|
|
|
}
|
|
|
|
|
|
|
|
validates :sha1,
|
|
|
|
presence: true,
|
|
|
|
uniqueness: { case_sensitive: false }
|
|
|
|
|
|
|
|
validates :sha256,
|
|
|
|
presence: true,
|
|
|
|
uniqueness: { case_sensitive: false }
|
|
|
|
|
|
|
|
###########
|
|
|
|
# Methods #
|
|
|
|
###########
|
|
|
|
|
2019-09-13 21:29:13 -04:00
|
|
|
def algo_class
|
|
|
|
raise NotImplementedError, "#{self.class}#algo_class"
|
|
|
|
end
|
|
|
|
|
|
|
|
def algo_variant
|
|
|
|
raise NotImplementedError, "#{self.class}#algo_variant"
|
|
|
|
end
|
|
|
|
|
2019-09-13 17:43:08 -04:00
|
|
|
def encrypt_private_key_pem
|
|
|
|
cipher = OpenSSL::Cipher::AES256.new
|
|
|
|
cipher.encrypt
|
|
|
|
|
|
|
|
self.private_key_pem_iv = cipher.random_iv.freeze
|
|
|
|
self.private_key_pem_secret = cipher.random_key.freeze
|
|
|
|
|
|
|
|
self.private_key_pem_ciphertext = [
|
|
|
|
cipher.update(private_key_pem),
|
|
|
|
cipher.final,
|
|
|
|
].join.freeze
|
|
|
|
|
|
|
|
private_key_pem_secret
|
|
|
|
end
|
|
|
|
|
|
|
|
def decrypt_private_key_pem
|
|
|
|
cipher = OpenSSL::Cipher::AES256.new
|
|
|
|
cipher.decrypt
|
|
|
|
|
|
|
|
cipher.iv = private_key_pem_iv
|
|
|
|
cipher.key = private_key_pem_secret
|
|
|
|
|
|
|
|
self.private_key_pem = [
|
|
|
|
cipher.update(private_key_pem_ciphertext),
|
|
|
|
cipher.final,
|
|
|
|
].join.freeze
|
|
|
|
end
|
2019-09-13 13:19:54 -04:00
|
|
|
end
|