1
0
Fork 0

Add method RSAPublicKey#decrypt_private_key_pem

This commit is contained in:
Alex Kotov 2019-09-12 07:29:35 +05:00
parent aff35166b7
commit 58dc02425f
Signed by: kotovalexarian
GPG key ID: 553C0EBBEB5D5F08
5 changed files with 55 additions and 33 deletions

View file

@ -10,11 +10,11 @@ class Staffs::X509Certificates::PrivateKeysController < ApplicationController
authorize [:staff, X509Certificate,
PublicKeyPrivateKey.new(@rsa_public_key)]
result = DecryptRSAPrivateKey.call public_key: @rsa_public_key
@rsa_public_key.decrypt_private_key_pem
respond_to do |format|
format.key do
send_data result.private_key_pem_cleartext, filename: 'private.key'
send_data @rsa_public_key.private_key_pem, filename: 'private.key'
end
end
end

View file

@ -1,24 +0,0 @@
# frozen_string_literal: true
class DecryptRSAPrivateKey
include Interactor
before :set_cipher
def call
context.public_key.private_key_pem = [
@cipher.update(context.public_key.private_key_pem_ciphertext),
@cipher.final,
].join.freeze
end
private
def set_cipher
@cipher = OpenSSL::Cipher::AES256.new
@cipher.decrypt
@cipher.iv = context.public_key.private_key_pem_iv
@cipher.key = context.public_key.private_key_pem_secret
end
end

View file

@ -10,4 +10,21 @@ class RSAPublicKey < ApplicationRecord
validates :public_key_pem, presence: true
validates :bits, inclusion: { in: [2048, 4096] }
###########
# Methods #
###########
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
end

View file

@ -1,7 +0,0 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DecryptRSAPrivateKey do
pending "add some examples to (or delete) #{__FILE__}"
end

View file

@ -20,4 +20,40 @@ RSpec.describe RSAPublicKey do
describe '#private_key_pem_ciphertext' do
it { is_expected.not_to validate_presence_of :private_key_pem_ciphertext }
end
describe '#decrypt_private_key_pem' do
let(:cleartext) { OpenSSL::PKey::RSA.new.to_pem }
before do
cipher = OpenSSL::Cipher::AES256.new
cipher.encrypt
subject.private_key_pem_iv = cipher.random_iv
subject.private_key_pem_secret = cipher.random_key
subject.private_key_pem_ciphertext = [
cipher.update(cleartext),
cipher.final,
].join
end
specify do
expect(subject.decrypt_private_key_pem).to be_instance_of String
end
specify do
expect(subject.decrypt_private_key_pem).to be_frozen
end
specify do
expect(subject.decrypt_private_key_pem).to equal subject.private_key_pem
end
specify do
expect { subject.decrypt_private_key_pem }.to \
change(subject, :private_key_pem)
.from(nil)
.to(cleartext)
end
end
end