Class: SmartHealthCardsTestKit::Utils::PrivateKey

Inherits:
Key
  • Object
show all
Defined in:
lib/smart_health_cards_test_kit/utils/private_key.rb

Overview

A key used for signing JWS

Constant Summary

Constants inherited from Key

Key::BASE, Key::DIGEST

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Key

#coordinates, enforce_valid_key_type!, from_jwk, #group, #initialize, #kid, #public_coordinates, #to_json, #to_jwk

Constructor Details

This class inherits a constructor from SmartHealthCardsTestKit::Utils::Key

Class Method Details

.from_file(path) ⇒ Object



8
9
10
11
# File 'lib/smart_health_cards_test_kit/utils/private_key.rb', line 8

def self.from_file(path)
  pem = OpenSSL::PKey::EC.new(File.read(path))
  PrivateKey.new(pem)
end

.generate_key(file_path: nil) ⇒ Object



21
22
23
24
25
# File 'lib/smart_health_cards_test_kit/utils/private_key.rb', line 21

def self.generate_key(file_path: nil)
  key = OpenSSL::PKey::EC.generate('prime256v1')
  File.write(file_path, key.to_pem) if file_path
  PrivateKey.new(key)
end

.load_from_or_create_from_file(path) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/smart_health_cards_test_kit/utils/private_key.rb', line 13

def self.load_from_or_create_from_file(path)
  if File.exist?(path)
    from_file(path)
  else
    generate_key(file_path: path)
  end
end

Instance Method Details

#public_key ⇒ Object



31
32
33
34
35
36
37
# File 'lib/smart_health_cards_test_kit/utils/private_key.rb', line 31

def public_key
  return @public_key if @public_key

  pub = OpenSSL::PKey::EC.new('prime256v1')
  pub.public_key = @key.public_key
  @public_key = PublicKey.new(pub)
end

#sign(payload) ⇒ Object



27
28
29
# File 'lib/smart_health_cards_test_kit/utils/private_key.rb', line 27

def sign(payload)
  asn1_to_raw(@key.sign(OpenSSL::Digest.new('SHA256'), payload), self)
end