Class: Acmesmith::AccountKey

Inherits:
Object
  • Object
show all
Defined in:
lib/acmesmith/account_key.rb

Defined Under Namespace

Classes: PassphraseRequired, PrivateKeyDecrypted

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(private_key, passphrase = nil) ⇒ AccountKey

Returns a new instance of AccountKey.

Parameters:

  • private_key (String, OpenSSL::PKey::RSA)
  • passphrase (String, nil) (defaults to: nil)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/acmesmith/account_key.rb', line 16

def initialize(private_key, passphrase = nil)
  case private_key
  when String
    @raw_private_key = private_key
    if passphrase
      self.key_passphrase = passphrase 
    else
      begin
        @private_key = OpenSSL::PKey::RSA.new(@raw_private_key) { nil }
      rescue OpenSSL::PKey::RSAError
        # may be encrypted
      end
    end
  when OpenSSL::PKey::RSA
    @private_key = private_key
  else
    raise TypeError, 'private_key is expected to be a String or OpenSSL::PKey::RSA'
  end
end

Class Method Details

.generate(bit_length = 2048) ⇒ Acmesmith::AccountKey

Parameters:

  • bit_length (Integer) (defaults to: 2048)

Returns:



10
11
12
# File 'lib/acmesmith/account_key.rb', line 10

def self.generate(bit_length = 2048)
  new OpenSSL::PKey::RSA.new(bit_length)
end

Instance Method Details

#export(passphrase, cipher: OpenSSL::Cipher.new('aes-256-cbc')) ⇒ String

Returns PEM.

Returns:

  • (String)

    PEM



56
57
58
59
60
61
62
# File 'lib/acmesmith/account_key.rb', line 56

def export(passphrase, cipher: OpenSSL::Cipher.new('aes-256-cbc'))
  if passphrase
    private_key.export(cipher, passphrase)
  else
    private_key.export
  end
end

#key_passphrase=(pw) ⇒ Object

Try to decrypt private_key if encrypted.

Parameters:

  • pw (String)

    passphrase for encrypted PEM

Raises:



39
40
41
42
43
44
45
46
# File 'lib/acmesmith/account_key.rb', line 39

def key_passphrase=(pw)
  raise PrivateKeyDecrypted, 'private_key already given' if @private_key

  @private_key = OpenSSL::PKey::RSA.new(@raw_private_key, pw)

  @raw_private_key = nil
  nil
end

#private_keyOpenSSL::PKey::RSA

Returns:

  • (OpenSSL::PKey::RSA)

Raises:



50
51
52
53
# File 'lib/acmesmith/account_key.rb', line 50

def private_key
  return @private_key if @private_key
  raise PassphraseRequired, 'key_passphrase required'
end