Class: HealthCards::PrivateKey

Inherits:
Key
  • Object
show all
Defined in:
lib/health_cards/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 HealthCards::Key

Class Method Details

.from_file(path) ⇒ Object



6
7
8
9
# File 'lib/health_cards/private_key.rb', line 6

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

.generate_key(file_path: nil) ⇒ Object



19
20
21
22
23
# File 'lib/health_cards/private_key.rb', line 19

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



11
12
13
14
15
16
17
# File 'lib/health_cards/private_key.rb', line 11

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_keyObject



29
30
31
32
33
34
35
# File 'lib/health_cards/private_key.rb', line 29

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



25
26
27
# File 'lib/health_cards/private_key.rb', line 25

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