pythoncryptographyasn.1dercbor

From base64-encoded public key in DER format to COSE key, in Python


I have a base64-encoded public key in DER format. In Python, how can I convert it into a COSE key?

Here is my failed attempt:

from base64 import b64decode
from cose.keys import CoseKey

pubkeyder = "...=="
decCborData.key = CoseKey.decode(b64decode(pubkeyder))

Solution

  • The posted key is an EC key for curve P-256 in X.509 format.

    With an ASN.1 parser (e.g. https://lapo.it/asn1js/) the x and y coordinates can be determined:

    x: 0x1AF1EA7FB498B65BDEBCEC80FE7A3E8B5FD67264B46CE60FD5B80FFA92538D39
    y: 0x013A9422F9FEC87BAE35E56165F5AA2ACCC98A449984E94AF81FE6FD55B6BB14
    

    Then the COSE key can be generated simply as follows:

    from cose.keys import EC2Key
    
    pub_x = bytes.fromhex('1AF1EA7FB498B65BDEBCEC80FE7A3E8B5FD67264B46CE60FD5B80FFA92538D39')
    pub_y = bytes.fromhex('013A9422F9FEC87BAE35E56165F5AA2ACCC98A449984E94AF81FE6FD55B6BB14')
    cose_pub_key = EC2Key(crv='P_256', x=pub_x, y=pub_y)
    

    For details, s. the cose library documentation and RFC8152, CBOR Object Signing and Encryption (COSE), especially chapter 13.


    The determination of the x and y coordinates can also be done programmatically, e.g. with PyCryptodome:

    from Crypto.PublicKey import ECC
    import base64
    
    der = base64.b64decode('MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGvHqf7SYtlvevOyA/no+i1/WcmS0bOYP1bgP+pJTjTkBOpQi+f7Ie6415WFl9aoqzMmKRJmE6Ur4H+b9Vba7FA==')
    key = ECC.import_key(der)
    pub_x = key.pointQ.x.to_bytes()
    pub_y = key.pointQ.y.to_bytes()