77
88import requests
99
10+ from cryptojwt .jwk .ec import NIST2SEC
1011from cryptojwt .jwk .hmac import new_sym_key
1112from .exception import DeSerializationNotPossible
1213from .exception import JWKException
1516from .jwk .ec import ECKey
1617from .jwk .ec import new_ec_key
1718from .jwk .hmac import SYMKey
19+ from .jwk .jwk import dump_jwk
20+ from .jwk .jwk import import_jwk
1821from .jwk .rsa import RSAKey
1922from .jwk .rsa import import_private_rsa_key_from_file
2023from .jwk .rsa import new_rsa_key
@@ -67,7 +70,7 @@ def rsa_init(spec):
6770 Example of specification::
6871 {'size':2048, 'use': ['enc', 'sig'] }
6972
70- Using the spec above 2 RSA keys would be minted, one for
73+ Using the spec above 2 RSA keys would be minted, one for
7174 encryption and one for signing.
7275 :param spec:
7376 :return: KeyBundle
@@ -439,8 +442,8 @@ def get(self, typ="", only_active=True):
439442 def keys (self ):
440443 """
441444 Return all keys after having updated them
442-
443- :return: List of all keys
445+
446+ :return: List of all keys
444447 """
445448 self ._uptodate ()
446449
@@ -462,7 +465,7 @@ def active_keys(self):
462465 def remove_keys_by_type (self , typ ):
463466 """
464467 Remove keys that are of a specific type.
465-
468+
466469 :param typ: Type of key (rsa, ec, oct, ..)
467470 """
468471 _typs = [typ .lower (), typ .upper ()]
@@ -474,7 +477,7 @@ def __str__(self):
474477 def jwks (self , private = False ):
475478 """
476479 Create a JWKS as a JSON document
477-
480+
478481 :param private: Whether private key information should be included.
479482 :return: A JWKS JSON representation of the keys in this bundle
480483 """
@@ -493,8 +496,8 @@ def jwks(self, private=False):
493496 def append (self , key ):
494497 """
495498 Add a key to list of keys in this bundle
496-
497- :param key: Key to be added
499+
500+ :param key: Key to be added
498501 """
499502 self ._keys .append (key )
500503
@@ -505,8 +508,8 @@ def extend(self, keys):
505508 def remove (self , key ):
506509 """
507510 Remove a specific key from this bundle
508-
509- :param key: The key that should be removed
511+
512+ :param key: The key that should be removed
510513 """
511514 try :
512515 self ._keys .remove (key )
@@ -700,15 +703,16 @@ def build_key_bundle(key_conf, kid_template=""):
700703 An example of such a specification::
701704
702705 keys = [
703- {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]},
706+ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"], 'size': 2048 },
704707 {"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"},
705- {"type": "EC", "crv": "P-256", "use": ["enc"], "kid": "ec.2"}
708+ {"type": "EC", "crv": "P-256", "use": ["enc"], "kid": "ec.2"},
709+ {"type": "OCT", "bytes":}
706710 ]
707711
708712 Keys in this specification are:
709713
710714 type
711- The type of key. Presently only 'rsa' and 'ec ' supported.
715+ The type of key. Presently only 'rsa', 'ec' and 'oct ' supported.
712716
713717 key
714718 A name of a file where a key can be found. Only works with PEM encoded
@@ -801,6 +805,7 @@ def type_order(kd1, kd2):
801805
802806 return None
803807
808+
804809def kid_order (kd1 , kd2 ):
805810 """Order key descriptions by kid."""
806811 try :
@@ -992,3 +997,54 @@ def unique_keys(keys):
992997 unique .append (k )
993998
994999 return unique
1000+
1001+
1002+ DEFAULT_SYM_KEYSIZE = 32
1003+ DEFAULT_RSA_KEYSIZE = 2048
1004+ DEFAULT_RSA_EXP = 65537
1005+ DEFAULT_EC_CURVE = 'P-256'
1006+
1007+
1008+ def key_gen (type , kid = '' , ** kwargs ):
1009+ """
1010+ Create a key and return it as a JWK.
1011+
1012+ :param type: Key type (RSA, EC, OCT)
1013+ :param kid:
1014+ :param kwargs: key specific keyword arguments
1015+ RSA: size, exp
1016+ EC: crv
1017+ SYM: bytes
1018+ """
1019+ if type .upper () == 'RSA' :
1020+ keysize = kwargs .get ("size" , DEFAULT_RSA_KEYSIZE )
1021+ public_exponent = kwargs .get ("exp" , DEFAULT_RSA_EXP )
1022+ _key = new_rsa_key (public_exponent = public_exponent , key_size = keysize , kid = kid )
1023+ elif type .upper () == 'EC' :
1024+ crv = kwargs .get ("crv" , DEFAULT_EC_CURVE )
1025+ if crv not in NIST2SEC :
1026+ logging .error ("Unknown curve: %s" , crv )
1027+ raise ValueError ("Unknown curve: {}" .format (crv ))
1028+ _key = new_ec_key (crv = crv , kid = kid )
1029+ elif type .upper () in ["SYM" , "OCT" ]:
1030+ keysize = kwargs .get ("bytes" , 24 )
1031+ randomkey = os .urandom (keysize )
1032+ _key = SYMKey (key = randomkey , kid = kid )
1033+ else :
1034+ logging .error ("Unknown key type: %s" , type )
1035+ raise ValueError ("Unknown key type: %s" .format (type ))
1036+
1037+ return _key
1038+
1039+
1040+ def init_key (filename , type , kid = "" , ** kwargs ):
1041+ if os .path .isfile (filename ):
1042+ _old_key = import_jwk (filename )
1043+
1044+ if _old_key .kty == type :
1045+ if not kid or _old_key .kid == kid :
1046+ return _old_key
1047+
1048+ _new_key = key_gen (type , kid , ** kwargs )
1049+ dump_jwk (filename , _new_key )
1050+ return _new_key
0 commit comments