COSE (CBOR Object Signing and Encryption)

raw JSON →
0.9.dev8 verified Fri May 01 auth: no python

A pure Python implementation of CBOR Object Signing and Encryption (COSE) as defined in RFC 8152. Current version 0.9.dev8, pre-release with ongoing development. Cadence: irregular, pre-release.

pip install cose
error ImportError: cannot import name 'EncryptMessage' from 'cose'
cause Trying to import from top-level package instead of submodule.
fix
Use: from cose.messages import EncryptMessage
error AttributeError: module 'cose' has no attribute 'CoseKey'
cause CoseKey is in cose.keys, not in top-level cose.
fix
Use: from cose.keys import CoseKey
error KeyError: 'kty'
cause Passing a dict with string keys instead of using the library's enum types.
fix
Use library types like KtyEC2 instead of strings: key = CoseKey.from_dict({'kty': KtyEC2, ...})
gotcha The library is in pre-release (0.9.dev8). APIs may change without notice.
fix Pin to a specific version and test compatibility.
gotcha Imports are deep: submodules like messages, keys, algorithms, headers are not exported at top level.
fix Use full paths, e.g., from cose.messages import EncryptMessage.
gotcha Many COSE objects require manual construction of key parameters and headers; no high-level helper for common patterns.
fix Refer to the official RFC 8152 and library examples for correct parameter values.

Create a simple EC2 key. For real use, provide proper key material.

from cose.keys import CoseKey
from cose.keys.keyparam import KpKty, KpAlg, KpKeyOps
from cose.keys.keytype import KtyEC2
from cose.keys.keyops import SignOp, VerifyOp, EncryptOp, DecryptOp
from cose.algorithms import Es256
from cose.messages import EncryptMessage, SignMessage
from cose.headers import Algorithm, ContentType

# Create an EC2 key for signing
import os
private_key_bytes = os.urandom(32)  # dummy for demo
key = CoseKey.from_dict({
    'kty': KtyEC2,
    'crv': 'P-256',
    'x': os.urandom(32),
    'y': os.urandom(32),
    'd': private_key_bytes,
    'alg': Es256,
})
print(f"Created key: {key}")