Skip to content

Commit

Permalink
Encryp and decrypt methods according to flow. PKCS5 + PBE + AES
Browse files Browse the repository at this point in the history
  • Loading branch information
aldosolorzano committed Dec 26, 2018
1 parent 9904c47 commit 2119db7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 14 deletions.
37 changes: 23 additions & 14 deletions lib/mifiel/crypto.rb
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
require_relative '../core_extensions.rb'
CoreExtensions.load

module Mifiel
module Crypto
autoload :PBE, 'mifiel/crypto/pbe'
autoload :Response, 'mifiel/crypto/response'
autoload :AES, 'mifiel/crypto/aes'
autoload :ECIES, 'mifiel/crypto/ecies'
autoload :PKCS5, 'mifiel/crypto/pkcs5'
end
end

class String
def bth
unpack('H*').first
end

def htb
Array(self).pack('H*')
end
def self.decrypt(asn1, pass)
pkcs5 = Mifiel::Crypto::PKCS5.parse(asn1.force_binary)
params = pkcs5.values
params[:data] = params[:cipher_text]
params[:key] =
Mifiel::Crypto::PBE.derive_key({ password: pass }.merge(params.slice(:salt, :iterations, :key_size)))
Mifiel::Crypto::AES.decrypt(params.slice(:key, :data, :iv, :cipher))
end

def force_binary
return htb if match?(/^[0-9A-F]+$/i)
return self if bth.match?(/^[0-9A-F]+$/i)
raise ArgumentError, 'Invalid encoding, hex or binary'
def self.encrypt(document, password)
params = {
salt: Mifiel::Crypto::PBE.random_salt,
iterations: Mifiel::Crypto::PBE::ITERATIONS,
password: password
}
params[:key] = Mifiel::Crypto::PBE.derive_key(params)
params[:iv] = Mifiel::Crypto::AES.random_iv
params[:data] = document
params[:cipher_text] = Mifiel::Crypto::AES.encrypt(params.slice(:key, :iv, :data))
Mifiel::Crypto::PKCS5.new(params.slice(:salt, :iv, :iterations, :cipher_text))
end
end
end
20 changes: 20 additions & 0 deletions spec/mifiel/crypto_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
describe Mifiel::Crypto do
pkcs5_fixture = JSON.parse(File.read('spec/fixtures/pkcs5.json'), symbolize_names: true)
describe '#Crypto' do
pkcs5_fixture[:valid].each do |v|
describe "ASN1: #{v[:asn1]}" do
it 'Should decrypt message' do
decrypted = Mifiel::Crypto.decrypt(v[:asn1], v[:password])
expect(decrypted).to eq(pkcs5_fixture[:plain_text])
end
end
it "Should encrypt a document, password: #{v[:password]}" do
pdf = File.read('spec/fixtures/example.pdf')
encrypted = Mifiel::Crypto.encrypt(pdf, v[:password])
encrypted_parsed = Mifiel::Crypto::PKCS5.parse(encrypted.to_der)
expect(encrypted).to be_a Mifiel::Crypto::PKCS5
expect(encrypted == encrypted_parsed).to be true
end
end
end
end

0 comments on commit 2119db7

Please sign in to comment.