Class: ActionMailerX509::X509

Inherits:
Object
  • Object
show all
Defined in:
lib/action_mailer_x509/x509.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ X509

pass_phrase cipher_type_str certificate and rsa_key or certificate_p12



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/action_mailer_x509/x509.rb', line 13

def initialize(attrs = {})
  attrs.symbolize_keys!

  attrs.reverse_merge!(pass_phrase: '', cipher_type_str: 'des')
  if attrs[:certificate_p12]
    p12 = OpenSSL::PKCS12.new(prepare_value(attrs[:certificate_p12]), attrs[:pass_phrase])
    @certificate = p12.certificate
    @rsa_key = p12.key
  elsif attrs[:certificate] and attrs[:rsa_key]
    @certificate = OpenSSL::X509::Certificate.new(prepare_value(attrs[:certificate]))
    @rsa_key = OpenSSL::PKey::RSA.new(prepare_value(attrs[:rsa_key]), attrs[:pass_phrase])
  else
    raise Exception.new('Wrong configuration')
  end

  @cipher = OpenSSL::Cipher.new(attrs[:cipher_type_str])

  @certificate_store = OpenSSL::X509::Store.new
  @certificate_store.add_cert(certificate)
end

Instance Attribute Details

#certificateObject

Returns the value of attribute certificate.



8
9
10
# File 'lib/action_mailer_x509/x509.rb', line 8

def certificate
  @certificate
end

#certificate_storeObject

Returns the value of attribute certificate_store.



8
9
10
# File 'lib/action_mailer_x509/x509.rb', line 8

def certificate_store
  @certificate_store
end

#cipherObject

Returns the value of attribute cipher.



8
9
10
# File 'lib/action_mailer_x509/x509.rb', line 8

def cipher
  @cipher
end

#rsa_keyObject

Returns the value of attribute rsa_key.



8
9
10
# File 'lib/action_mailer_x509/x509.rb', line 8

def rsa_key
  @rsa_key
end

Instance Method Details

#decode(encrypted_text) ⇒ Object



39
40
41
42
43
44
# File 'lib/action_mailer_x509/x509.rb', line 39

def decode(encrypted_text)
  pkcs7 = read(encrypted_text)
  pkcs7.decrypt(@rsa_key, certificate)
rescue => e
  raise DecodeError.new(e.message)
end

#encode(text) ⇒ Object



34
35
36
37
# File 'lib/action_mailer_x509/x509.rb', line 34

def encode(text)
  write OpenSSL::PKCS7.encrypt([certificate], text, cipher)
  #OpenSSL::PKCS7.encrypt([certificate], text, cipher, OpenSSL::PKCS7::BINARY)
end

#sign(text) ⇒ Object



46
47
48
# File 'lib/action_mailer_x509/x509.rb', line 46

def sign(text)
  write OpenSSL::PKCS7.sign(certificate, rsa_key, text, [], OpenSSL::PKCS7::DETACHED|OpenSSL::PKCS7::BINARY)
end

#verify(text) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/action_mailer_x509/x509.rb', line 50

def verify(text)
  #set the signer's certificates are not chain verified.
  result = read(text).verify(nil, @certificate_store, nil, OpenSSL::PKCS7::NOVERIFY)
  result ? read(text).data : raise(VerificationError.new('Verification failed !!!'))
rescue => e
  raise VerificationError.new(e.message)
end