1- from cwt import COSEKey
21from typing import Union
32
43from pycose .keys import CoseKey
87from cryptography .x509 .oid import NameOID
98from cryptography .x509 import Certificate
109from cryptography .hazmat .primitives import hashes , serialization
10+ from cryptography .hazmat .primitives .asymmetric import ec , ed25519
1111
1212def selfsigned_x509cert (cert_info : dict [str , Any ], private_key : CoseKey , encoding : str = "DER" ) -> Union [Certificate , bytes ]:
1313 """
@@ -31,8 +31,24 @@ def selfsigned_x509cert(cert_info: dict[str, Any], private_key: CoseKey, encodin
3131
3232 if not private_key :
3333 raise ValueError ("private_key must be set" )
34+
35+ # convert the private key to a cryptography private key instance
36+ if hasattr (private_key , "kty" ) and private_key .kty is not None and hasattr (private_key .kty , "identifier" ):
37+ if private_key .kty .identifier == 2 : # EC2Key
38+ private_key_inst = ec .derive_private_key (
39+ int .from_bytes (private_key ['d' ], byteorder = "big" ), ec .SECP256R1 ()
40+ )
41+ elif private_key .kty .identifier == 1 : # OKPKey
42+ private_key_inst = ed25519 .Ed25519PrivateKey .from_private_bytes (
43+ private_key ['d' ]
44+ )
45+ else :
46+ raise ValueError (f"Unsupported key type: { private_key .kty } " )
47+ else :
48+ raise ValueError ("private_key.kty or private_key.kty.identifier is not set or unknown" )
49+
3450
35- ckey = COSEKey . from_bytes ( private_key . encode () )
51+ public_key_inst = private_key_inst . public_key ( )
3652
3753 name_attributes = []
3854 if "country_name" in cert_info :
@@ -53,7 +69,7 @@ def selfsigned_x509cert(cert_info: dict[str, Any], private_key: CoseKey, encodin
5369 ).issuer_name (
5470 issuer
5571 ).public_key (
56- ckey . key . public_key ()
72+ public_key_inst
5773 ).serial_number (
5874 x509 .random_serial_number ()
5975 )
@@ -82,7 +98,7 @@ def selfsigned_x509cert(cert_info: dict[str, Any], private_key: CoseKey, encodin
8298 # Sign our certificate with our private key
8399 )
84100
85- cert = cert_builder .sign (ckey . key , hashes .SHA256 ())
101+ cert = cert_builder .sign (private_key_inst , hashes .SHA256 ())
86102
87103 if not encoding :
88104 return cert
0 commit comments