Class: COSE::Key::OKP

Inherits:
CurveKey show all
Defined in:
lib/cose/key/okp.rb

Constant Summary collapse

KTY_OKP =
1

Constants inherited from CurveKey

CurveKey::LABEL_CRV, CurveKey::LABEL_D, CurveKey::LABEL_X

Constants inherited from Base

Base::LABEL_ALG, Base::LABEL_BASE_IV, Base::LABEL_KEY_OPS, Base::LABEL_KID, Base::LABEL_KTY

Instance Attribute Summary

Attributes inherited from CurveKey

#crv, #d, #x

Attributes inherited from Base

#alg, #base_iv, #key_ops, #kid

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CurveKey

#initialize, keyword_arguments_for_initialize

Methods inherited from Base

deserialize, from_map, #initialize, #serialize

Constructor Details

This class inherits a constructor from COSE::Key::CurveKey

Class Method Details

.enforce_type(map) ⇒ Object



12
13
14
15
16
# File 'lib/cose/key/okp.rb', line 12

def self.enforce_type(map)
  if map[LABEL_KTY] != KTY_OKP
    raise "Not an OKP key"
  end
end

.from_pkey(pkey) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/cose/key/okp.rb', line 18

def self.from_pkey(pkey)
  curve = Curve.by_pkey_name(pkey.oid) || raise("Unsupported edwards curve #{pkey.oid}")
  attributes = { crv: curve.id }

  asymmetric_key = pkey.public_to_der
  public_key_bit_string = OpenSSL::ASN1.decode(asymmetric_key).value.last.value
  attributes[:x] = public_key_bit_string
  begin
    asymmetric_key = pkey.private_to_der
    private_key = OpenSSL::ASN1.decode(asymmetric_key).value.last.value
    curve_private_key = OpenSSL::ASN1.decode(private_key).value
    attributes[:d] = curve_private_key
  rescue OpenSSL::PKey::PKeyError
    # work around lack of https://github.com/ruby/openssl/pull/527, otherwise raises this error
    # with message 'i2d_PKCS8PrivateKey_bio: error converting private key' for public keys
    nil
  end

  new(**attributes)
end

Instance Method Details

#curveObject



65
66
67
# File 'lib/cose/key/okp.rb', line 65

def curve
  Curve.find(crv)
end

#mapObject



39
40
41
# File 'lib/cose/key/okp.rb', line 39

def map
  super.merge(LABEL_KTY => KTY_OKP)
end

#to_pkeyObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/cose/key/okp.rb', line 43

def to_pkey
  if curve
    private_key_algo = OpenSSL::ASN1::Sequence.new(
      [OpenSSL::ASN1::ObjectId.new(curve.pkey_name)]
    )
    seq = if d
            version = OpenSSL::ASN1::Integer.new(0)
            curve_private_key = OpenSSL::ASN1::OctetString.new(d).to_der
            private_key = OpenSSL::ASN1::OctetString.new(curve_private_key)
            [version, private_key_algo, private_key]
          else
            public_key = OpenSSL::ASN1::BitString.new(x)
            [private_key_algo, public_key]
          end

    asymmetric_key = OpenSSL::ASN1::Sequence.new(seq)
    OpenSSL::PKey.read(asymmetric_key.to_der)
  else
    raise "Unsupported curve #{crv}"
  end
end