Python Binding

Added in version 1.11.14.

The Python binding is based on the ffi module of botan and the ctypes module of the Python standard library.

The versioning of the Python module follows the major versioning of the C++ library. So for Botan 2, the module is named botan2 while for Botan 3 it is botan3.

Versioning

botan3.version_major() int

Returns the major number of the library version.

botan3.version_minor() int

Returns the minor number of the library version.

botan3.version_patch() int

Returns the patch number of the library version.

botan3.ffi_api_version() int

Returns the version of the FFI API provided by the library

botan3.version_string() str

Returns a free form version string for the library

Utilities

botan3.const_time_compare(x: str | bytes, y: str | bytes) bool

Compare two strings or byte vectors, returning True if they are equal. The comparison of the contents runs in constant time; unequal lengths are rejected immediately.

botan3.MPILike = str | ForwardRef('MPI') | typing.Any | None

Alias for parameters that get turned into an MPI.

class botan3.BotanException(message, rc=0)

Base exception for all exceptions raised from this module

Create an exception with message. If rc is a nonzero library error code, the description of that error plus the library’s most recent exception message are appended.

error_code() int

Returns the library error code associated with this exception, or zero if there is none

Random Number Generators

class botan3.RandomNumberGenerator(rng_type: str = 'system', **kwargs)

Previously rng

Type ‘user’ also allowed (userspace HMAC_DRBG seeded from system rng). The system RNG is very cheap to create, as just a single file handle or CSP handle is kept open, from first use until shutdown, no matter how many ‘system’ rng instances are created. Thus it is easy to use the RNG in a one-off way, with botan.RandomNumberGenerator().get(32).

For some use cases it can be useful to provide a custom RNG implementation. Use ‘custom’ as the rng_type and provide the get_callback= and add_entropy_callback= arguments. The latter is optional. get_callback takes an integer and is expected to return a bytes object with the requested number of random bytes. add_entropy_callback takes a bytes object containing entropy bytes and is expected to add the given entropy to the RNG.

When Botan is configured with TPM 2.0 support, also ‘tpm2’ is allowed to instantiate a TPM-backed RNG. Note that this requires passing additional named arguments tpm2_context= with a TPM2Context and (optionally) tpm2_sessions= with one or more TPM2Session objects.

Constructs a RandomNumberGenerator of type rng_type. Available RNG types are:

  • ‘system’: Adapter to the operating system’s RNG

  • ‘user’: Software-PRNG that is auto-seeded by the system RNG

  • ‘null’: Mock-RNG that fails if randomness is pulled from it

  • ‘hwrng’: Adapter to an available hardware RNG (platform dependent)

  • ‘tpm2’: Adapter to a TPM 2.0 RNG

    (needs additional named arguments tpm2_context= and, optionally, tpm2_sessions=)

  • ‘custom’: Adapter to user-defined callbacks

    (needs additional named arguments get_callback= and, optionally, add_entropy_callback=)

Create a RandomNumberGenerator of the named type.

reseed(bits: int = 256)

Meaningless on system RNG, on userspace RNG causes a reseed/rekey

reseed_from_rng(source_rng: RandomNumberGenerator, bits: int = 256)

Take bits from the source RNG and use it to seed self

add_entropy(seed: str | bytes)

Add some unpredictable seed data to the RNG

get(length: int) bytes

Return some bytes

generate_with_input(length: int, additional_input: bytes) bytes

Generate random bytes with additional input mixed in (for DRBGs)

static drbg(drbg_name: str, seed: bytes) RandomNumberGenerator

Create a seeded DRBG (e.g. “HMAC_DRBG(SHA-256)”)

The seed should be the concatenation of entropy, nonce, and personalization string.

Hash Functions

class botan3.HashFunction(algo: str | c_void_p)

Previously hash_function

The algo param is a string (eg ‘SHA-1’, ‘SHA-384’, ‘BLAKE2b’)

Create a hash function object for the named algorithm

copy_state() HashFunction

Returns an independent copy of this object, with the same state

algo_name() str

Returns the name of this algorithm

clear()

Clear state

output_length() int

Return output length in bytes

block_size() int

Return block size in bytes

security_level() int

Return the estimated security level, in bits, wrt collision resistance

update(x: str | bytes)

Add some input

final() bytes

Returns the hash of all input provided, resets for another message.

eXtensible Output Functions

class botan3.XOF(algo: str | c_void_p)

eXtensible Output Function (XOF). The algo param is a string (e.g ‘SHAKE-256’, ‘Ascon-XOF128’)

Create a XOF object for the named algorithm

copy_state() XOF

Returns an independent copy of this object, with the same state

clear()

Clear state

update(x: str | bytes)

Add some input

output(length: int) bytes

Returns length bytes of output from the XOF after all input was provided

accepts_input() bool

Returns True if the XOF can accept more input, False if it is in output-only mode.

algo_name() str

Returns the name of this algorithm

block_size() int

Return block size in bytes

Message Authentication Codes

class botan3.MsgAuthCode(algo: str)

Previously message_authentication_code

The constructor algo param is a string (eg ‘HMAC(SHA-256)’, ‘Poly1305’, ‘CMAC(AES-256)’)

Create a message authentication code object for the named algorithm

clear()

Clear internal state including the key

algo_name() str

Returns the name of this algorithm

output_length() int

Return the output length in bytes

minimum_keylength() int

Returns the minimum key length in bytes

maximum_keylength() int

Returns the maximum key length in bytes

keylength_modulo() int

Returns the granularity of key lengths; any valid key length is a multiple of this value

set_key(key: bytes)

Set the key

set_nonce(nonce: bytes)

Set the nonce. Only a few MACs, such as GMAC, take a nonce

update(x: str | bytes)

Add some input

final() bytes

Returns the MAC of all input provided, resets for another message with the same key.

Ciphers

class botan3.SymmetricCipher(algo: str, encrypt: bool = True)

Previously cipher

The algorithm is specified as a string (eg ‘AES-128/GCM’, ‘Serpent/OCB(12)’, ‘Threefish-512/EAX’). Set encrypt to False for decryption.

Create a cipher object for the named algorithm, for encryption unless encrypt is False

algo_name() str

Returns the name of this algorithm

default_nonce_length() int

Returns default nonce length

update_granularity() int

Returns update block size. Call to update() must provide input of exactly this many bytes

ideal_update_granularity() int

Returns a multiple of update_granularity() which is likely to provide the best performance

key_length() tuple[int, int]

Returns a tuple of the minimum and maximum key lengths, in bytes

minimum_keylength() int

Returns the minimum key length in bytes

maximum_keylength() int

Returns the maximum key length in bytes

tag_length() int

Returns the tag length (0 for unauthenticated modes)

is_authenticated() bool

Returns True if this is an AEAD mode

valid_nonce_length(nonce_len) bool

Returns True if nonce_len is a valid nonce len for this mode

reset()

Reset the nonce and any state associated with the message processed so far, retaining the key. Equivalent to clear() followed by setting the same key again.

clear()

Resets all state

set_key(key: bytes)

Set the key

set_assoc_data(ad: bytes)

Sets the associated data. Fails if this is not an AEAD mode

start(nonce: bytes)

Start processing a message using nonce

update(txt: str | bytes)

Consumes input text and returns output. Input text must be of update_granularity() length. Alternately, always call finish with the entire message, avoiding calls to update entirely

finish(txt: str | bytes | None = None)

Finish processing (with an optional final input). May throw if message authentication checks fail, in which case all plaintext previously processed must be discarded. You may call finish() with the entire message

class botan3.BlockCipher(algo: str | c_void_p)

A raw block cipher, eg ‘AES-128’ or ‘Threefish-512’

This is a low level interface which does not provide any confidentiality on its own; most applications should use SymmetricCipher instead.

Create a block cipher object for the named algorithm

set_key(key: bytes)

Set the key

encrypt(pt: bytes) Array

Encrypt the input, whose length must be a multiple of block_size()

decrypt(ct: bytes) Array

Decrypt the input, whose length must be a multiple of block_size()

algo_name() str

Returns the name of this algorithm

clear()

Clear internal state including the key

block_size() int

Returns the block size in bytes

minimum_keylength() int

Returns the minimum key length in bytes

maximum_keylength() int

Returns the maximum key length in bytes

keylength_modulo() int

Returns the granularity of key lengths; any valid key length is a multiple of this value

Bcrypt

botan3.bcrypt(passwd: str, rng_obj: RandomNumberGenerator, work_factor=10)

Provided the password and an RNG object, returns a bcrypt string

botan3.check_bcrypt(passwd: str, passwd_hash: str)

Check a bcrypt hash against the provided password, returning True iff the password matches.

PBKDF

botan3.pbkdf(algo: str, password: str, out_len: int, iterations: int = 100000, salt: bytes | None = None) tuple[bytes, int, bytes]

Runs a PBKDF2 algo specified as a string (eg ‘PBKDF2(SHA-256)’, ‘PBKDF2(CMAC(Blowfish))’). Runs with specified iterations, with meaning depending on the algorithm. The salt can be provided or otherwise is randomly chosen. In any case it is returned from the call.

Returns out_len bytes of output (or potentially less depending on the algorithm and the size of the request).

Returns tuple of salt, iterations, and psk

botan3.pbkdf_timed(algo: str, password: str, out_len: int, ms_to_run: int = 300, salt: bytes | None = None) tuple[bytes, int, bytes]

Runs for as many iterations as needed to consumed ms_to_run milliseconds on whatever we’re running on. Returns tuple of salt, iterations, and psk

Scrypt

Added in version 2.8.0.

botan3.scrypt(out_len: int, password: str, salt: str | bytes, n: int = 1024, r: int = 8, p: int = 8) bytes

Runs Scrypt key derivation function over the specified password and salt using Scrypt parameters N, r, p.

Argon2

botan3.argon2(variant: str, out_len: int, password: str, salt: str | bytes, m: int = 256, t: int = 1, p: int = 1) bytes

Runs the Argon2 password hashing function, returning out_len bytes

The variant should be “Argon2i”, “Argon2d”, or “Argon2id”. m specifies the memory used during processing, in kibibytes, t the number of passes, and p the parallelism.

KDF

botan3.kdf(algo: str, secret: bytes, out_len: int, salt: bytes, label: bytes) bytes

Performs a key derivation function (such as “HKDF(SHA-384)”) over the provided secret and salt values. Returns a value of the specified length.

Public Key

class botan3.PublicKey(obj: c_void_p | None = None)

Previously public_key

Create a public key object wrapping the given FFI handle, or an empty one. Applications should use one of the load methods instead.

classmethod load(val: str | bytes) PublicKey

Load a public key. The value should be a PEM or DER blob.

classmethod load_rsa(n: MPILike, e: MPILike) PublicKey

Load an RSA public key giving the modulus and public exponent as integers.

classmethod load_dsa(p: MPILike, q: MPILike, g: MPILike, y: MPILike) PublicKey

Load a DSA public key giving the parameters and public value as integers.

classmethod load_dh(p: MPILike, g: MPILike, y: MPILike) PublicKey

Load a Diffie-Hellman public key giving the parameters and public value as integers.

classmethod load_elgamal(p: MPILike, q: MPILike, g: MPILike, y: MPILike) PublicKey

Load an ElGamal public key giving the parameters and public value as integers.

classmethod load_ecdsa(curve: str, pub_x: MPILike, pub_y: MPILike) PublicKey

Load an ECDSA public key giving the curve as a string (like “secp256r1”) and the public point as a pair of integers giving the affine coordinates.

classmethod load_ecdsa_sec1(curve: str, sec1_encoding: str | bytes) PublicKey

Load an ECDSA public key giving the curve as a string (like “secp256r1”) and the public point in SEC1 format.

classmethod load_ecdh(curve: str, pub_x: MPILike, pub_y: MPILike) PublicKey

Load an ECDH public key giving the curve as a string (like “secp256r1”) and the public point as a pair of integers giving the affine coordinates.

classmethod load_ecdh_sec1(curve: str, sec1_encoding: str | bytes) PublicKey

Load an ECDH public key giving the curve as a string (like “secp256r1”) and the public point in SEC1 format.

classmethod load_sm2(curve: str, pub_x: MPILike, pub_y: MPILike) PublicKey

Load a SM2 public key giving the curve as a string (like “sm2p256v1”) and the public point as a pair of integers giving the affine coordinates.

classmethod load_sm2_sec1(curve: str, sec1_encoding: str | bytes) PublicKey

Load a SM2 public key giving the curve as a string (like “sm2p256v1”) and the public point in SEC1 format.

classmethod load_kyber(key: bytes) PublicKey

Load a Kyber public key from the raw encoding of the public key

classmethod load_ml_kem(mlkem_mode: str, key: bytes) PublicKey

Load an ML-KEM public key giving the mode as a string (like “ML-KEM-512”) and the raw encoding of the public key.

classmethod load_ml_dsa(mldsa_mode: str, key: bytes) PublicKey

Load an ML-DSA public key giving the mode as a string (like “ML-DSA-4x4”) and the raw encoding of the public key.

classmethod load_slh_dsa(slhdsa_mode: str, key: bytes) PublicKey

Load an SLH-DSA public key giving the mode as a string (like “SLH-DSA-SHAKE-128f”) and the raw encoding of the public key.

classmethod load_frodokem(frodo_mode: str, key: bytes) PublicKey

Load a FrodoKEM public key giving the mode as a string (like “FrodoKEM-640-SHAKE”) and the raw encoding of the public key.

classmethod load_classic_mceliece(cmce_mode: str, key: bytes) PublicKey

Load a Classic McEliece public key giving the mode as a string (like “348864f”) and the raw encoding of the public key.

classmethod load_x25519(key: bytes) PublicKey

Return a public X25519 key from 32 raw bytes

classmethod load_x448(key: bytes) PublicKey

Return a public X448 key from 56 raw bytes

check_key(rng_obj: RandomNumberGenerator, strong: bool = True) bool

Test the key for consistency. If strong is True then more expensive tests are performed.

estimated_strength() int

Returns the estimated strength of this key against known attacks (NFS, Pollard’s rho, etc)

algo_name() str

Returns the algorithm name

export(pem: bool = False) str | bytes

Exports the public key using the usual X.509 SPKI representation. If pem is True, the result is a PEM encoded string. Otherwise it is a binary DER value.

to_der() bytes

Like self.export(False)

to_pem() str

Like self.export(True)

to_raw() bytes

Exports the key in its canonical raw encoding. This might not be available for all key types and raise an exception in that case.

view_kyber_raw_key() bytes

Deprecated: use to_raw() instead

fingerprint(hash_algorithm: str = 'SHA-256') str

Returns a hash of the public key

get_field(field_name: str) int

Return an integer field related to the public key. The valid field names vary depending on the algorithm. For example RSA public modulus can be extracted with rsa_key.get_field("n").

object_identifier() OID

Returns the associated OID

get_public_point() bytes

Returns the SEC1 uncompressed encoding of the public point, if this is an EC key

used_explicit_encoding() bool

Returns True if this key was decoded from a structure which encoded the elliptic curve using explicit parameters rather than a named curve. Raises an exception if the key is not an EC key.

get_group() ECGroup

Return the group associated with the key if the key is an EC key. Raises an exception if the key is not an EC key.

Private Key

class botan3.PrivateKey(obj: c_void_p | None = None)

Previously private_key

Create a private key object wrapping the given FFI handle, or an empty one. Applications should use create or one of the load methods instead.

classmethod load(val: str | bytes, passphrase: str | None = None) PrivateKey

Return a private key (DER or PEM formats accepted)

classmethod create(algo: str, params: str | int | tuple[int, int], rng_obj: RandomNumberGenerator) PrivateKey

Creates a new private key. The parameter type/value depends on the algorithm. For “rsa” is is the size of the key in bits. For “ecdsa” and “ecdh” it is a group name (for instance “secp256r1”). For “ecdh” there is also a special case for groups “curve25519” and “x448” (which are actually completely distinct key types with a non-standard encoding).

classmethod create_ec(algo: str, ec_group: ECGroup, rng_obj: RandomNumberGenerator) PrivateKey

Creates a new ec private key.

classmethod load_rsa(p: MPILike, q: MPILike, e: MPILike) PrivateKey

Return a private RSA key

classmethod load_dsa(p: MPILike, q: MPILike, g: MPILike, x: MPILike) PrivateKey

Return a private DSA key

classmethod load_dh(p: MPILike, g: MPILike, x: MPILike) PrivateKey

Return a private DH key

classmethod load_elgamal(p: MPILike, q: MPILike, g: MPILike, x: MPILike) PrivateKey

Return a private ElGamal key

classmethod load_ecdsa(curve: str, x: MPILike) PrivateKey

Return a private ECDSA key

classmethod load_ecdh(curve: str, x: MPILike) PrivateKey

Return a private ECDH key

classmethod load_sm2(curve: str, x: MPILike) PrivateKey

Return a private SM2 key

classmethod load_kyber(key: bytes) PrivateKey

Return a private Kyber key from the raw encoding of the private key

classmethod load_ml_kem(mlkem_mode: str, key: bytes) PrivateKey

Return a private ML-KEM key

classmethod load_ml_dsa(mldsa_mode: str, key: bytes) PrivateKey

Return a private ML-DSA key

classmethod load_slh_dsa(slh_dsa: str, key: bytes) PrivateKey

Return a private SLH-DSA key

classmethod load_frodokem(frodo_mode: str, key: bytes) PrivateKey

Return a private FrodoKEM key giving the mode as a string (like “FrodoKEM-640-SHAKE”) and the raw encoding of the private key.

classmethod load_classic_mceliece(cmce_mode: str, key: bytes) PrivateKey

Return a private Classic McEliece key giving the mode as a string (like “348864f”) and the raw encoding of the private key.

classmethod load_x25519(key: bytes) PrivateKey

Return a private X25519 key from 32 raw bytes

classmethod load_x448(key: bytes) PrivateKey

Return a private X448 key from 56 raw bytes

check_key(rng_obj: RandomNumberGenerator, strong: bool = True) bool

Test the key for consistency. If strong is True then more expensive tests are performed.

algo_name() str

Returns the algorithm name

get_public_key() PublicKey

Return a public_key object

to_der() bytes

Return the DER encoded private key (unencrypted). Like self.export(False)

to_pem() str

Return the PEM encoded private key (unencrypted). Like self.export(True)

to_raw() bytes

Exports the key in its canonical raw encoding. This might not be available for all key types and raise an exception in that case.

view_kyber_raw_key() bytes

Deprecated: use to_raw() instead

export(pem: bool = False) str | bytes

Exports the private key in PKCS8 format. If pem is True, the result is a PEM encoded string. Otherwise it is a binary DER value. The key will not be encrypted.

export_encrypted(passphrase: str, rng: RandomNumberGenerator, pem: bool = False, msec: int = 300, cipher: str | None = None, pbkdf: str | None = None)

Exports the private key in PKCS8 format, encrypted using the provided passphrase. If pem is True, the result is a PEM encoded string. Otherwise it is a binary DER value.

get_field(field_name: str) int

Return an integer field related to the public key. The valid field names vary depending on the algorithm. For example first RSA secret prime can be extracted with rsa_key.get_field("p"). This function can also be used to extract the public parameters.

object_identifier() OID

Return the associated OID

stateful_operation() bool

Return whether the key is stateful or not.

remaining_operations() int

If the key is stateful, return the number of remaining operations. Raises an exception if the key is not stateful.

get_private_key() ECScalar

Return the private value if the key is an EC key.

get_group() ECGroup

Return the group associated with the key if the key is an EC key. Raises an exception if the key is not an EC key.

Public Key Operations

class botan3.PKEncrypt(key: PublicKey, padding: str)

Previously pk_op_encrypt

Create an encryption operation using key and the named padding (eg “OAEP(SHA-256)”)

encrypt(msg: bytes, rng_obj: RandomNumberGenerator) bytes

Encrypt a message, returning the ciphertext

class botan3.PKDecrypt(key: PrivateKey, padding: str)

Previously pk_op_decrypt

Create a decryption operation using key and the named padding (eg “OAEP(SHA-256)”)

decrypt(msg: bytes) bytes

Decrypt a ciphertext, returning the plaintext

class botan3.PKSign(key: PrivateKey, padding: str, der: bool = False)

Previously pk_op_sign

Create a signature operation using key and the named padding, eg “PSS(SHA-256)”. If der is True then the signature is DER encoded.

update(msg: str | bytes)

Add more data to be signed

finish(rng_obj: RandomNumberGenerator) bytes

Returns the signature of the message provided so far, and resets for another message

class botan3.PKVerify(key: PublicKey, padding: str, der: bool = False)

Previously pk_op_verify

Create a verification operation using key and the named padding, eg “PSS(SHA-256)”. If der is True then the signature is expected to be DER encoded.

update(msg: str | bytes)

Add more data to be verified

check_signature(signature: str | bytes) bool

Returns True if the signature is valid for the message provided so far, and resets for another message

class botan3.PKKeyAgreement(key: PrivateKey, kdf_name: str)

Previously pk_op_key_agreement

Create a key agreement operation using key and the named KDF, eg “KDF2(SHA-256)”, or “Raw” to return the agreed value directly.

public_value() bytes

Returns the public value to be passed to the other party

underlying_output_length() int

Returns the length of the agreed value before the KDF is applied

agree(other: bytes, key_len: int, salt: bytes) bytes

Returns a key derived by the KDF.

class botan3.KemEncrypt(key: PublicKey, params: str)

Key encapsulation using a public key

Create an encapsulation operation using key and the named KDF, eg “KDF2(SHA-256)”, or “Raw” to return the shared secret directly.

shared_key_length(desired_key_len: int) int

Returns the length of the shared key produced for a request of desired_key_len bytes

encapsulated_key_length() int

Returns the length of the encapsulated key

create_shared_key(rng: RandomNumberGenerator, salt: bytes, desired_key_len: int) tuple[bytes, bytes]

Generate a new shared key, returning a tuple of the shared key and the encapsulated key to be sent to the holder of the private key

class botan3.KemDecrypt(key: PrivateKey, params: str)

Key decapsulation using a private key

Create a decapsulation operation using key and the named KDF, eg “KDF2(SHA-256)”, or “Raw” to return the shared secret directly.

shared_key_length(desired_key_len: int) int

Returns the length of the shared key produced for a request of desired_key_len bytes

decrypt_shared_key(salt: bytes, desired_key_len: int, encapsulated_key: bytes) bytes

Recover the shared key from the encapsulated key

TPM 2.0 Bindings

Added in version 3.6.0.

class botan3.TPM2Context(tcti_name_maybe_with_conf: str | None = None, tcti_conf: str | None = None)

TPM 2.0 Context object

Create a TPM 2.0 context optionally with a TCTI name and configuration, separated by a colon, or as separate parameters.

Construct a TPM2Context object with optional TCTI name and configuration.

static supports_botan_crypto_backend() bool

Returns True if the given build supports the Botan-based crypto backend.

enable_botan_crypto_backend(rng: RandomNumberGenerator)

Enables the Botan-based crypto backend. The passed rng MUST NOT be dependent on the TPM.

class botan3.TPM2UnauthenticatedSession(ctx: TPM2Context)

Session object that is not bound to any authentication credential. It provides basic parameter encryption between the application and the TPM.

Create a new unauthenticated session within the given TPM 2.0 context

Multiple Precision Integers (MPI)

Added in version 2.8.0.

class botan3.MPI(initial_value: TypeAliasForwardRef('MPILike') | c_void_p = None, radix: int | None = None)

Initialize an MPI object with specified value, left as zero otherwise. The initial_value should be an int, str, or MPI. The radix value should be set to 16 when initializing from a base 16 str value.

Most of the usual arithmetic operators (__add__, __mul__, etc) are defined.

Initialize an MPI, see the class documentation for the accepted values

classmethod random(rng_obj: RandomNumberGenerator, bits: int) MPI

Returns a new MPI with a random value of exactly bits bits

classmethod random_range(rng_obj: RandomNumberGenerator, lower: MPI, upper: MPI)

Returns a new MPI with a random value in the range [lower, upper)

to_bytes() Array

Returns the big-endian binary encoding of this value

is_negative() bool

Returns True if this value is less than zero

is_positive() bool

Returns True if this value is greater than or equal to zero

is_zero() bool

Returns True if this value is zero

is_odd() bool

Returns True if this value is odd

is_even() bool

Returns True if this value is even

flip_sign()

Negate this value in place

mod_mul(other: MPI, modulus: MPI) MPI

Return the multiplication product of self and other modulo modulus

gcd(other: MPI) MPI

Return the greatest common divisor of self and other

pow_mod(exponent: MPI, modulus: MPI) MPI

Return self to the exponent power modulo modulus

is_prime(rng_obj: RandomNumberGenerator, prob: int = 128) bool

Test if self is prime

inverse_mod(modulus: MPI) MPI

Return the inverse of self modulo modulus, or zero if no inverse exists

bit_count() int

Returns the size of this value in bits

byte_count() int

Returns the size of this value in bytes

get_bit(bit: int) bool

Returns the value of the specified bit

clear_bit(bit: int)

Set the specified bit to zero

set_bit(bit: int)

Set the specified bit to one

Object Identifiers (OID)

Added in version 3.8.0.

class botan3.OID(obj: c_void_p | None = None)

An ASN.1 object identifier

Create an OID wrapping the given FFI handle, or an empty one. Applications should use from_string instead.

classmethod from_string(value: str) OID

Create a new OID from dot notation or from a known name

to_string() str

Export the OID in dot notation

to_name() str

Export the OID as a name if it has one, else in dot notation

register(name: str)

Register the OID so that it may later be retrieved by the given name

EC Groups

Added in version 3.8.0.

class botan3.ECGroup(obj: c_void_p | None = None)

An elliptic curve group

Create an ECGroup wrapping the given FFI handle, or an empty one. Applications should use one of the from_* methods instead.

classmethod supports_application_specific_group() bool

Returns true if in this build configuration it is possible to register an application specific elliptic curve

classmethod supports_named_group(name: str) bool

Returns true if in this build configuration ECGroup.from_name(name) will succeed

classmethod from_params(oid: OID, p: MPI, a: MPI, b: MPI, base_x: MPI, base_y: MPI, order: MPI) ECGroup

Creates a new ECGroup from ec parameters

classmethod from_ber(ber: bytes) ECGroup

Creates a new ECGroup from a BER blob

classmethod from_pem(pem: str) ECGroup

Creates a new ECGroup from a PEM encoding

classmethod from_oid(oid: OID) ECGroup

Creates a new ECGroup from a group named by an OID

classmethod from_name(name: str) ECGroup

Creates a new ECGroup from a common group name

classmethod unregister(oid: OID) bool

Unregister a previously registered group

to_der() bytes

Export the group in DER encoding

to_pem() str

Export the group in PEM encoding

get_curve_oid() OID

Get the curve OID

get_p() MPI

Get the prime modulus of the field

get_a() MPI

Get the a parameter of the elliptic curve equation

get_b() MPI

Get the b parameter of the elliptic curve equation

get_g_x() MPI

Get the x coordinate of the base point

get_g_y() MPI

Get the y coordinate of the base point

get_order() MPI

Get the order of the base point

get_identity() ECPoint

Returns the identity element of this group

get_generator() ECPoint

Returns the base point of this group

class botan3.ECScalar(obj: c_void_p | None = None)

An integer modulo the order of an elliptic curve group

Create an ECScalar wrapping the given FFI handle, or an empty one. Applications should use random or from_mpi instead.

classmethod random(group: ECGroup, rng: RandomNumberGenerator) ECScalar

Create a new scalar with a random value

classmethod from_mpi(group: ECGroup, mpi: MPI) ECScalar

Convert from an MPI to a scalar. Raises an exception if the MPI is negative or too large.

to_mpi() MPI

Convert from a scalar to an MPI.

class botan3.ECPoint(obj: c_void_p | None = None)

A point on an elliptic curve

Create an ECPoint wrapping the given FFI handle, or an empty one. Applications should use one of the from_* methods instead.

classmethod identity(group: ECGroup) ECPoint

Create a point set to the group identity

classmethod generator(group: ECGroup) ECPoint

Create a point set to the group generator

classmethod from_xy(group: ECGroup, x: MPI, y: MPI) ECPoint

Create a point from a set of (x,y) integers. The integers must be within the field and must satisfy the curve equation.

classmethod from_bytes(group: ECGroup, buf: bytes) ECPoint

Create a point from a SEC1 compressed or uncompressed format.

is_identity()

Returns True if this point is the identity element of its group

negate() ECPoint

Returns the negation of this point

mul(scalar: ECScalar, rng: RandomNumberGenerator) ECPoint

Returns the product of this point and scalar. The RNG is used for blinding.

to_x_bytes() bytes

Get the fixed length encoding of the affine x coordinate

to_y_bytes() bytes

Get the fixed length encoding of the affine y coordinate

to_xy_bytes() bytes

Get the fixed length encoding of the affine x and y coordinates

to_uncompressed() bytes

Get the fixed length SEC1 uncompressed encoding

to_compressed() bytes

Get the fixed length SEC1 compressed encoding

Format Preserving Encryption (FE1 scheme)

Added in version 2.8.0.

class botan3.FormatPreservingEncryptionFE1(modulus: MPI, key: bytes, rounds: int = 5, compat_mode: bool = False)

Initialize an instance for format preserving encryption

Create an instance encrypting integers modulo modulus under key

encrypt(msg: MPILike, tweak: str | bytes) MPI

The msg should be a botan3.MPI or an object which can be converted to one

decrypt(msg: MPILike, tweak: str | bytes) MPI

The msg should be a botan3.MPI or an object which can be converted to one

HOTP

Added in version 2.8.0.

class botan3.HOTP(key: bytes, digest: str = 'SHA-1', digits: int = 6)

Counter based one time passwords (RFC 4226)

Create an HOTP instance using the given key, hash function, and number of digits

generate(counter: int) int

Generate an HOTP code for the provided counter

check(code: int, counter: int, resync_range: int = 0) tuple[bool, int]

Check if provided code is the correct code for counter. If resync_range is greater than zero, HOTP also checks up to resync_range following counter values.

Returns a tuple of (bool,int) where the boolean indicates if the code was valid, and the int indicates the next counter value that should be used. If the code did not verify, the next counter value is always identical to the counter that was passed in. If the code did verify and resync_range was zero, then the next counter will always be counter+1.

TOTP

class botan3.TOTP(key: bytes, digest: str = 'SHA-1', digits: int = 6, timestep: int = 30)

Time based one time passwords (RFC 6238)

Create a TOTP instance using the given key, hash function, number of digits, and time step in seconds

generate(timestamp: int | None = None) int

Generate the TOTP code for the given Unix timestamp, or for the current time

check(code: int, timestamp: int | None = None, acceptable_drift: int = 0) bool

Returns True if code is the correct code for the given Unix timestamp (or for the current time), allowing up to acceptable_drift time steps of clock skew in either direction

Key Wrapping

botan3.nist_key_wrap(kek: bytes, key: bytes, cipher: str | None = None) bytes

Wrap key under the key encryption key kek using the NIST SP 800-38F KW mode. The input length must be a multiple of 8 bytes. If cipher is not specified, AES with a key length matching kek is used.

botan3.nist_key_unwrap(kek: bytes, wrapped: bytes, cipher: str | None = None) bytes

Unwrap a key which was wrapped using nist_key_wrap

botan3.nist_key_wrap_padded(kek: bytes, key: bytes, cipher: str | None = None) bytes

Wrap key under the key encryption key kek using the NIST SP 800-38F KWP mode, which accepts an input of any length. If cipher is not specified, AES with a key length matching kek is used.

botan3.nist_key_unwrap_padded(kek: bytes, wrapped: bytes, cipher: str | None = None) bytes

Unwrap a key which was wrapped using nist_key_wrap_padded

Secure Remote Password protocol (SRP)

class botan3.Srp6ServerSession(group: str)

The server side of the SRP-6a password authenticated key exchange

Create a session using the named group (eg “modp/srp/2048”)

step1(verifier: bytes, hsh: str, rng: RandomNumberGenerator) bytes

Given the verifier stored for this user, returns the value B to send to the client

step2(a: bytes) bytes

Given the value A received from the client, returns the shared session key

botan3.srp6_generate_verifier(identifier: str, password: str, salt: bytes, group: str, hsh: str) bytes

Returns the verifier which the server stores for this user

botan3.srp6_client_agree(username: str, password: str, group: str, hsh: str, salt: bytes, b: bytes, rng: RandomNumberGenerator) tuple[bytes, bytes]

The client side of the SRP-6a password authenticated key exchange. Given the value b received from the server, returns a tuple of the value A to send to the server and the shared session key.

ZFEC

botan3.zfec_encode(k: int, n: int, input_bytes: bytes) list[bytes]

ZFEC-encode an input message according to the given parameters

Parameters:
  • k – the number of shares required to recover the original

  • n – the total number of shares

  • input_bytes – the input message, in bytes

Returns:

n arrays of bytes, each one containing a single share

botan3.zfec_decode(k: int, n: int, indexes: list[int], inputs: list[bytes]) list[bytes]

ZFEC decode

Parameters:
  • k – the number of shares required to recover the original

  • n – the total number of shares

  • indexes – which of the shares are we giving the decoder

  • inputs – the input shares (e.g. from a previous call to zfec_encode) which all must be the same length

Exactly k shares are needed to recover the data. Supplying more than k (index, share) pairs is allowed; the extras are ignored.

Returns:

a list of bytes containing the original shares decoded from the provided shares (in inputs)

SPAKE2+

Added in version 3.13.0.

class botan3.Spake2pParams(ciphersuite: str | None = None)

SPAKE2+ (RFC 9383) system parameters, selecting the elliptic curve group, the SPAKE2+ M/N group elements, and the hash function.

The ciphersuite is one of “P256-SHA256”, “P256-SHA512”, “P384-SHA256”, “P384-SHA512”, or “P521-SHA512”.

Create system parameters for one of the named ciphersuites

classmethod custom(group: ECGroup, seed: bytes, hash_fn: str) Spake2pParams

Create custom system parameters for an arbitrary group, deriving the M/N group elements from the seed using hash to curve (which not all groups support). Both peers must use the same group, seed, and hash.

share_size() int

Return the size in bytes of a key share (shareP or shareV)

confirmation_size() int

Return the size in bytes of a key confirmation message (confirmP or confirmV)

botan3.spake2p_derive_secret(params: Spake2pParams, password: str, prover_id: bytes = b'', verifier_id: bytes = b'', salt: bytes = b'') bytes

Derive a SPAKE2+ (RFC 9383) prover secret from a password, using Argon2id.

The returned secret is password equivalent, and must be protected accordingly. It is used with spake2p_registration_record and Spake2pProver

botan3.spake2p_registration_record(params: Spake2pParams, secret: bytes, rng: RandomNumberGenerator) bytes

Compute a SPAKE2+ registration record from a prover secret.

The registration record is provided to the verifier during registration.

class botan3.Spake2pProver(params: Spake2pParams, secret: bytes, prover_id: bytes = b'', verifier_id: bytes = b'', context: bytes = b'')

SPAKE2+ (RFC 9383) prover: the side which knows the password secret.

The expected message flow is

  • The prover calls generate_message and sends the result to the verifier

  • The verifier calls process_message on it and sends the result to the prover

  • The prover calls process_message on it, verifying the verifier’s key confirmation, and sends the resulting confirmation to the verifier

  • The verifier calls verify_confirmation on it

After the final step both sides can call shared_secret.

The identities and context must be agreed upon by both parties; the identities must additionally match the values used when deriving the prover secret.

generate_message(rng: RandomNumberGenerator) bytes

Generate the prover’s key share, which is sent to the verifier. Can be called only once.

process_message(peer_message: bytes, rng: RandomNumberGenerator) bytes

Consume the verifier’s response and return the prover’s key confirmation, which is sent to the verifier. Raises an exception if the verifier’s key confirmation is wrong, typically meaning the passwords do not match.

shared_secret() bytes

Return the shared secret. Only valid after process_message succeeded.

class botan3.Spake2pVerifier(params: Spake2pParams, record: bytes, prover_id: bytes = b'', verifier_id: bytes = b'', context: bytes = b'')

SPAKE2+ (RFC 9383) verifier: the side which stores only the registration record derived from the password. See Spake2pProver for the message flow.

The identities and context must be agreed upon by both parties; the identities must additionally match the values used when deriving the prover secret.

process_message(peer_message: bytes, rng: RandomNumberGenerator) bytes

Consume the prover’s key share and return the verifier’s response (its own key share followed by a key confirmation), which is sent to the prover. Can be called only once.

verify_confirmation(confirmation: bytes) None

Check the prover’s key confirmation. Raises an exception if the confirmation is wrong, meaning the prover does not know the password.

skip_confirmation() None

Skip checking the prover’s key confirmation, allowing shared_secret to be called without verify_confirmation. After calling this, no evidence has been received that the peer knows the password; it is intended solely for protocols which embed SPAKE2+ and perform the prover’s key confirmation themselves.

shared_secret() bytes

Return the shared secret. Only valid after verify_confirmation succeeded, or after skip_confirmation.

X509Cert

class botan3.X509Cert(filename: str | None = None, buf: bytes | None = None)

Class representing an X.509 certificate.

A certificate in PEM or DER format can be loaded from a file, with the filename argument, or from a bytestring, with the buf argument.

Load a certificate from either a file or a bytestring, but not both

time_starts() datetime

Return the time the certificate becomes valid, as a string in form “YYYYMMDDHHMMSSZ” where Z is a literal character reflecting that this time is relative to UTC.

time_expires() datetime

Return the time the certificate expires, as a string in form “YYYYMMDDHHMMSSZ” where Z is a literal character reflecting that this time is relative to UTC.

to_string() str

Format the certificate as a free-form string.

fingerprint(hash_algo: str = 'SHA-256') str

Return a fingerprint for the certificate, which is basically just a hash of the binary contents. Normally SHA-1 or SHA-256 is used, but any hash function is allowed.

serial_number() bytes

Return the serial number of the certificate.

authority_key_id() bytes

Return the authority key ID set in the certificate, which may be empty.

subject_key_id() bytes

Return the subject key ID set in the certificate, which may be empty.

subject_public_key_bits() bytes

Get the serialized representation of the public key included in this certificate.

subject_public_key() PublicKey

Get the public key included in this certificate as an object of class PublicKey.

subject_dn(key: str, index: int) str

Get a value from the subject DN field.

key specifies a value to get, for instance "Name" or "Country".

issuer_dn(key: str, index: int) str

Get a value from the issuer DN field.

key specifies a value to get, for instance "Name" or "Country".

hostname_match(hostname: str) bool

Return True if the Common Name (CN) field of the certificate matches a given hostname.

not_before() int

Return the time the certificate becomes valid, as seconds since epoch.

not_after() int

Return the time the certificate expires, as seconds since epoch.

allowed_usage(usage_list: list[str]) bool

Return True if the certificates Key Usage extension contains all constraints given in usage_list. Also return True if the certificate doesn’t have this extension. Example usage constraints are: "DIGITAL_SIGNATURE", "KEY_CERT_SIGN", "CRL_SIGN".

ext_ip_addr_blocks() tuple[list[tuple[int | None, list[tuple[tuple[int], tuple[int]]] | None]], list[tuple[int | None, list[tuple[tuple[int], tuple[int]]] | None]]]

Get values from the IP Address Blocks extension. If the extension is not present, an exception will be raised.

Returns all values in the extension, in the form of (v4, v6), where both contain a list of tuples of type (int | None, list[…]). The first element of each tuple is the SAFI, it may be None to indicate no SAFI is present. The second element is a list of elements of type tuple[tuple[int], tuple[int]], where each element is a single address range. Each element contains two tuples of equal length, 4 for IPv4 families and 16 for IPv6 families. The values are the minimum and maximum addresses of the range respectively. If the particular family is marked as “inherit”, the outer tuple will contain None as its second element instead of a list of ranges.

ext_as_blocks_asnum() list[tuple[int, int]] | None

Get values from the AS Blocks extension. If the extension is not present, an exception will be raised.

Returns all AS numbers contained in the extension. Returns a list of tuples, where each tuple is a range, and its inner elements are the minimum and maximum values of the range respectively. If AS numbers are marked as “inherit”, None is returned instead. If AS numbers are not present in the extension at all, this raises an exception.

ext_as_blocks_rdi() list[tuple[int, int]] | None

Get values from the AS Blocks extension. If the extension is not present, an exception will be raised.

Get all RDIs contained in the extension. Returns a list of tuples, where each tuple is a range, and its inner elements are the minimum and maximum values of the range respectively. If RDIs are marked as “inherit”, None is returned instead. If RDIs are not present in the extension at all, this raises an exception.

verify(intermediates: list[X509Cert] | None = None, trusted: list[X509Cert] | None = None, trusted_path: str | None = None, required_strength: int = 0, hostname: str | None = None, reference_time: int = 0, crls: list[X509CRL] | None = None) int

Verify a certificate. Returns 0 if validation was successful, returns a positive error code if the validation was unsuccessful.

intermediates is a list of untrusted subauthorities.

trusted is a list of trusted root CAs.

The trusted_path refers to a directory where one or more trusted CA certificates are stored.

Set required_strength to indicate the minimum key and hash strength that is allowed. For instance setting to 80 allows 1024-bit RSA and SHA-1. Setting to 110 requires 2048-bit RSA and SHA-256 or higher. Set to zero to accept a default.

If hostname is given, it will be checked against the certificates CN field.

Set reference_time to be the time which the certificate chain is validated against. Use zero (default) to use the current system clock.

crls is a list of CRLs issued by either trusted or untrusted authorities.

classmethod validation_status(error_code: int) str

Return an informative string associated with the verification return code.

is_revoked(crl: X509CRL) bool

Check if the certificate (self) is revoked on the given crl.

X509CRL

class botan3.X509CRLReason(*values)

The reason a certificate was revoked, as encoded in the CRL entry reason code

UNSPECIFIED = 0

No specific reason was given for the revocation.

KEY_COMPROMISE = 1

The subject’s private key is known or suspected to have been compromised.

CA_COMPROMISE = 2

A CA certificate’s private key is known or suspected to have been compromised.

AFFILIATION_CHANGED = 3

The subject’s name or other information changed, without any suspicion of key compromise.

SUPERSEDED = 4

The certificate has been superseded, without any suspicion of key compromise.

CESSATION_OF_OPERATION = 5

The certificate is no longer needed, without any suspicion of key compromise.

CERTIFICATE_HOLD = 6

The certificate is temporarily suspended (placed on hold).

REMOVE_FROM_CRL = 8

Used only in delta CRLs to remove an entry from the base CRL (e.g. a hold was lifted).

PRIVILEGE_WITHDRAWN = 9

A privilege contained in the certificate has been withdrawn.

AA_COMPROMISE = 10

An attribute authority’s private key is known or suspected to have been compromised.

classmethod to_bits(reason: X509CRLReason) int

Returns the numeric encoding of reason

classmethod from_bits(reason: int) X509CRLReason

Returns the reason corresponding to the numeric encoding reason

class botan3.X509CRLEntry

A single revoked certificate, as recorded in a CRL

Create an entry with no associated certificate; applications should use create

classmethod create(cert: X509Cert, reason: X509CRLReason)

Create a new entry revoking cert for the given reason

serial_number() MPI

Returns the serial number of the revoked certificate

revocation_date() int

Returns the time the certificate was revoked, as seconds since epoch

reason() X509CRLReason

Returns the reason the certificate was revoked

class botan3.X509CRL(filename: str | None = None, buf: bytes | None = None)

Class representing an X.509 Certificate Revocation List.

A CRL in PEM or DER format can be loaded from a file, with the filename argument, or from a bytestring, with the buf argument.

Load a CRL from either a file or a bytestring. If neither is given the object is empty.

classmethod create(rng: RandomNumberGenerator, ca_cert: X509Cert, ca_key: PrivateKey, issue_time: int, next_update: int, hash_fn: str | None = None, padding: str | None = None) X509CRL

Create a new, empty CRL issued by ca_cert and signed using ca_key.

issue_time is the time the CRL becomes valid, in seconds since epoch, and next_update the number of seconds after that until the CRL expires. The signature hash_fn and padding may be None to use a default.

revoke(rng: RandomNumberGenerator, ca_cert: X509Cert, ca_key: PrivateKey, issue_time: int, next_update: int, new_entries: list[X509CRLEntry], hash_fn: str | None = None, padding: str | None = None) X509CRL

Returns a new CRL, again issued by ca_cert and signed using ca_key, containing the entries of self plus new_entries.

revoked() list[X509CRLEntry]

Returns the list of entries contained in this CRL

verify(key: PublicKey) bool

Returns True if the signature on this CRL is valid for the given public key