cedarcode / cose-ruby

Ruby implementation of RFC 8152 CBOR Object Signing and Encryption (COSE)
https://rubygems.org/gems/cose
MIT License
16 stars 10 forks source link

Generating COSE signatures #65

Open atyndall opened 1 month ago

atyndall commented 1 month ago

It's ambiguous in the docs that this library doesn't assist you with the generation of COSE signatures, some of the examples imply it might, but it became clear to me after testing that this doesn't seem to be supported?

It would be good to make this clearer, or add the functionality.

To assist any users who come by the Github and have the same issue, here is some sample code I wrote that can successfully generate the COSE signatures.

It's not production ready, but it does work, and proves the core concepts.

class ExampleSigner
  attr_reader :algorithm, :sig_method

  def initialize(algorithm, sig_method)
    @algorithm = COSE::Algorithm.find(algorithm)
    @sig_method = COSE.const_get(sig_method)
  end

  def generate_key
    signer.generate_signing_key.verify_key.serialize
  end

  def sign(unsigned_payload)
    CBOR::Tagged.new(sig_method.tag, [
                       CBOR.encode(protected_header),
                       unprotected_header,
                       unsigned_payload,
                       signature(unsigned_payload)
                     ]).to_cbor
  end

  def verify(signed_payload, verify_key)
    signed_cwt = sig_method.deserialize(signed_payload)
    cose_key = COSE::Key::EC2.from_pkey(signer.class::VerifyKey.deserialize(verify_key).send(:__getobj__))
    signed_cwt.verify(cose_key)
  end

  private

  def signer
    @signer ||= algorithm.send(:signature_algorithm_class).new(**algorithm.send(:signature_algorithm_parameters))
  end

  def protected_header
    { COSE::SecurityMessage::Headers::HEADER_LABEL_ALG => algorithm.id }
  end

  def unprotected_header
    {}
  end

  def external_aad
    nil
  end

  def sig_structure(unsigned_payload)
    CBOR.encode([
                  sig_method::CONTEXT,
                  CBOR.encode(protected_header),
                  external_aad || COSE::SecurityMessage::ZERO_LENGTH_BIN_STRING,
                  unsigned_payload
                ])
  end

  def signature(unsigned_payload)
    signer.sign(sig_structure(unsigned_payload))
  end
end

CWT_ISSUER = 1
CWT_EXPIRATION = 4
CWT_NOT_BEFORE = 5
CWT_ISSUED_AT = 6

# Example CWT payload
unsigned_payload = {CWT_ISSUER=>'my_issuer',
           CWT_EXPIRATION=>1_735_689_599,
           CWT_NOT_BEFORE=>1_704_067_200,
           CWT_ISSUED_AT=>1_727_998_532}

s = ExampleSigner.new('ES256', 'Sign1')
public_key = s.generate_key

signed_payload = s.sign(unsigned_payload)

if s.verify(signed_payload, public_key)
  puts "Verified successfully!"
else
  puts "Verification failed!"
end