Base keys¶
The cryptographic keys involved for the secretbox API, for the hash API and for key derivation are very similar. All of them are derived from a base key class.
Because they inherit from BaseKey class, HashKeys, SecretBoxKeys and Masterkeys have the following properties:
- They encapsulate a 32-byte key that's allocated using guarded heap memory.
- A random key can be generated using the
genclass method. - They implement the Buffer protocol and can by used as
bytes-likeobjects. - They can be exported as a
strusing the__str__method (base64 encoding is used). - They can be written to a file using the
writetomethod. - They can be read from a file using the
read_frommethod.
class BaseKey ¶
Base class for keys used in symmetric cryptography (e.g., hashing, encryption).
Users should not instantiate this class directly. Instead, use one of the subclasses.
The memory to store the key is allocated using guarded heap allocations, similar to what is done in libsodium.
BaseKey implements the buffer protocol, allowing it to be used as a bytes-like object.
__bool__()
¶
Returns True if the key is not zero, False otherwise.
Returns:
-
bool–True if the key is not zero, False otherwise.
__init__(b=None)
¶
Initialize the BaseKey with an optional bytes object.
Parameters:
-
b(bytes | None, default:None) –A bytes object representing the key. If None, a zero key will be created.
Raises:
-
MemoryError–If memory allocation for the key fails.
-
TypeError–If the provided key is not a bytes object.
-
ValueError–If the provided key is not 32 bytes long.
__str__()
¶
Returns a base64-encoded representation of the key.
Returns:
-
str–A string representing the key in base64 encoding.
gen()
classmethod
¶
is_zero()
¶
read_from(reader)
classmethod
¶
Create a key from a reader.
Parameters:
-
reader(Reader) –A reader object that supports the read method.
Returns:
-
Self–A new instance of BaseKey read from the provided reader.
Raises:
-
TypeError–If the provided reader does not have a 'read' method.
-
ValueError–If the read data is not 32 bytes long.