Class: JWK::ECKey

Inherits:
Key
  • Object
show all
Defined in:
lib/jwk/ec_key.rb

Constant Summary collapse

CURVE_NAMES =
{
  'prime256v1' => 'P-256',
  'secp384r1' => 'P-384',
  'secp521r1' => 'P-521'
}.freeze
COORD_SIZE =
{
  'P-256' => 32,
  'P-384' => 48,
  'P-521' => 64
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Key

from_json, from_pem, #to_json, validate_kty!, #x5t_s256

Constructor Details

#initialize(key) ⇒ ECKey

Returns a new instance of ECKey.



17
18
19
20
# File 'lib/jwk/ec_key.rb', line 17

def initialize(key)
  @key = key
  validate
end

Class Method Details

.from_openssl(k) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/jwk/ec_key.rb', line 77

def from_openssl(k)
  if k.is_a? OpenSSL::PKey::EC::Point
    from_openssl_public(k)
  else
    from_openssl_private(k)
  end
end

Instance Method Details

#crvObject



56
57
58
# File 'lib/jwk/ec_key.rb', line 56

def crv
  @key['crv']
end

#private?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/jwk/ec_key.rb', line 26

def private?
  !@key['d'].nil?
end

#public?Boolean

Returns:

  • (Boolean)


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

def public?
  true
end

#raw_public_keyObject



66
67
68
69
70
71
72
73
74
# File 'lib/jwk/ec_key.rb', line 66

def raw_public_key
  raw_x = Utils.int_to_binary(x)
  raw_y = Utils.int_to_binary(y)

  raw_x = pad_coord_for_crv(crv, raw_x)
  raw_y = pad_coord_for_crv(crv, raw_y)

  "\x04#{raw_x}#{raw_y}"
end

#to_openssl_keyObject



43
44
45
46
47
48
49
50
# File 'lib/jwk/ec_key.rb', line 43

def to_openssl_key
  if private?
    OpenSSL::PKey.read(to_pem)
  else
    group = OpenSSL::PKey::EC::Group.new(self.class::CURVE_NAMES.key(crv))
    OpenSSL::PKey::EC::Point.new(group, OpenSSL::BN.new(raw_public_key.unpack('H*')[0], 16))
  end
end

#to_pemObject

Raises:

  • (NotImplementedError)


36
37
38
39
40
41
# File 'lib/jwk/ec_key.rb', line 36

def to_pem
  raise NotImplementedError, 'Cannot convert an EC public key to PEM.' unless private?

  asn = ASN1.ec_private_key(crv, d, raw_public_key)
  generate_pem('EC PRIVATE', asn)
end

#to_sObject



52
53
54
# File 'lib/jwk/ec_key.rb', line 52

def to_s
  to_pem
end

#validateObject



30
31
32
33
34
# File 'lib/jwk/ec_key.rb', line 30

def validate
  unless @key['x'] && @key['y'] && ['P-256', 'P-384', 'P-521'].include?(@key['crv'])
    raise JWK::InvalidKey, 'Invalid EC key.'
  end
end