Class: Firma

Inherits:
Struct
  • Object
show all
Defined in:
lib/firma.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#fileObject

Returns the value of attribute file

Returns:

  • (Object)

    the current value of file



5
6
7
# File 'lib/firma.rb', line 5

def file
  @file
end

Class Method Details

.create_certificate_from_key(key) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/firma.rb', line 35

def create_certificate_from_key(key)
  name = "CN=ruby/DC=subskribas"
  certificate = OpenSSL::X509::Certificate.new

  certificate.version     = 2
  certificate.serial      = 0
  certificate.not_before  = Time.now
  certificate.not_after   = Time.now + 3600
  certificate.public_key  = key.public_key
  certificate.subject     = OpenSSL::X509::Name.parse(name)

  create_temp_file(["certificate", ".crt"], certificate.to_pem)
end

.create_temp_file(name, content) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/firma.rb', line 72

def create_temp_file(name, content)
  filename, extension = name
  random = (0...8).map{65.+(rand(25)).chr}.join
  temp_name = "#{Dir.tmpdir}/#{filename + random + extension}"

  File.open(temp_name, "w") { |io| io << content }
end

.generate_keys(passphrase) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/firma.rb', line 49

def generate_keys(passphrase)
  rsa_key = OpenSSL::PKey::RSA.new(2048)

  key = create_temp_file(["key", ".pem"], rsa_key.to_pem)

  public_key = create_temp_file(
    ["public_key", ".pem"],
    rsa_key.public_key.to_pem
  )

  cipher = OpenSSL::Cipher::Cipher.new("AES-128-CBC")
  secure_key = rsa_key.export(cipher, passphrase)

  private_key = create_temp_file(["private_key", ".pem"], secure_key)

  {
    key:          key,
    public_key:   public_key,
    private_key:  private_key,
    certificate:  create_certificate_from_key(rsa_key)
  }
end

.is_signed?(file) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/firma.rb', line 27

def is_signed?(file)
  new(file).is_signed?
end

.sign(file, options = {}) ⇒ Object



31
32
33
# File 'lib/firma.rb', line 31

def sign(file, options = {})
  new(file).sign(options)
end

Instance Method Details

#is_signed?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/firma.rb', line 22

def is_signed?
  Origami::PDF.read(file).is_signed?
end

#sign(options) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/firma.rb', line 6

def sign(options)
  key = OpenSSL::PKey::RSA.new(
    File.open(options.fetch(:key)),
    options.fetch(:passphrase)
  )

  certificate = OpenSSL::X509::Certificate.new(
    File.open(options.fetch(:certificate))
  )

  pdf = Origami::PDF.read(file)

  pdf.sign(certificate, key)
  pdf.save(file)
end