11"""
22This module contains functions to help manage keys used in PASETO protocols.
33
4- It includes an early implementation of Algorithm Lucidity.
4+ It includes an implementation of Algorithm Lucidity.
55https://github.com/paseto-standard/paseto-spec/blob/master/docs/02-Implementation-Guide/03-Algorithm-Lucidity.md
66
77A PASERK implementation may supersede this module in the future.
1414
1515import pysodium
1616
17- KEY_PREFIX = b"k"
18- KEY_LENGHT = 32
17+ _KEY_PREFIX = b"k"
18+ _KEY_LENGHT = 32
1919
20- TYPE_LOCAL = b".local."
21- TYPE_PUBLIC = b".public."
22- TYPE_SECRET = b".secret."
20+ _TYPE_LOCAL = b".local."
21+ _TYPE_PUBLIC = b".public."
22+ _TYPE_SECRET = b".secret."
2323
2424
25- def _create_symmetric_key (version : int ) -> bytes :
25+ def _create_symmetric_key (version : int , raw_key_material : bytes = b"" ) -> bytes :
2626 """Return a new symmetric key."""
2727 _validate_version (version )
28- return _get_key_prefix ( version , TYPE_LOCAL ) + urlsafe_b64encode (
29- os .urandom (KEY_LENGHT )
30- )
28+ if not raw_key_material :
29+ raw_key_material = os .urandom (_KEY_LENGHT )
30+ return _serialize_key ( version , _TYPE_LOCAL , raw_key_material )
3131
3232
33- def _create_asymmetric_key (version : int ) -> Tuple [bytes , bytes ]:
33+ def _create_asymmetric_key (
34+ version : int ,
35+ raw_public_key_material : bytes = b"" ,
36+ raw_secret_key_material : bytes = b"" ,
37+ ) -> Tuple [bytes , bytes ]:
3438 """Return new public and secret keys."""
3539 _validate_version (version )
36- raw_public_key , raw_secret_key = pysodium . crypto_sign_seed_keypair (
37- os . urandom ( pysodium . crypto_sign_SEEDBYTES )
38- )
39-
40- public_key = _get_key_prefix ( version , TYPE_PUBLIC ) + urlsafe_b64encode (
41- raw_public_key
42- )
43- secret_key = _get_key_prefix ( version , TYPE_SECRET ) + urlsafe_b64encode (
44- raw_secret_key
45- )
40+ if not raw_public_key_material or not raw_secret_key_material :
41+ (
42+ raw_public_key_material ,
43+ raw_secret_key_material ,
44+ ) = pysodium . crypto_sign_seed_keypair (
45+ os . urandom ( pysodium . crypto_sign_SEEDBYTES )
46+ )
47+
48+ public_key : bytes = _serialize_key ( version , _TYPE_PUBLIC , raw_public_key_material )
49+ secret_key : bytes = _serialize_key ( version , _TYPE_SECRET , raw_secret_key_material )
4650 return public_key , secret_key
4751
4852
@@ -63,7 +67,7 @@ def _validate_version(version: int) -> bool:
6367
6468def _get_key_prefix (version : int , key_type : bytes ) -> bytes :
6569 """Return key prefix for serialization."""
66- return KEY_PREFIX + str (version ).encode () + key_type
70+ return _KEY_PREFIX + str (version ).encode () + key_type
6771
6872
6973def _verify_key (key : bytes , version : int , key_type : bytes ) -> bool :
0 commit comments