### Install cryptography with uv Source: https://cryptography.io/en/latest/_sources/index.rst.txt Install the cryptography library using uv. ```console $ uv add cryptography ``` -------------------------------- ### Initialize Development Environment Source: https://cryptography.io/en/latest/_sources/development/getting-started.rst.txt Install nox and initialize the local build environment. ```console $ # Create a virtualenv and activate it $ # Set up your cryptography build environment $ pip install nox $ nox -e local ``` -------------------------------- ### Starting New Test Vector Source: https://cryptography.io/en/latest/development/custom-vectors/rsa-oaep-sha2 Reads a line from the BufferedReader to identify the start of a new test vector example. Throws an IOException if the expected header is missing. ```java private void startNewTest(BufferedReader br) throws IOException { String line = br.readLine(); if (!line.startsWith(EXAMPLE)) throw new IOException("Example Header Missing"); } ``` -------------------------------- ### Install and Run Nox for Development Environment Source: https://cryptography.io/en/latest/development/getting-started Install nox using pip and then run 'nox -e local' to set up the development environment. This command handles the installation of necessary development dependencies. ```bash # Create a virtualenv and activate it # Set up your cryptography build environment pip install nox nox -e local ``` -------------------------------- ### ConcatKDFHMAC Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to initialize and use ConcatKDFHMAC for key derivation and verification. Ensure the salt and otherinfo are consistent for verification. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC salt = os.urandom(16) otherinfo = b"concatkdf-example" ckdf = ConcatKDFHMAC( algorithm=hashes.SHA256(), length=32, salt=salt, otherinfo=otherinfo, ) key = ckdf.derive(b"input key") ckdf = ConcatKDFHMAC( algorithm=hashes.SHA256(), length=32, salt=salt, otherinfo=otherinfo, ) ckdf.verify(b"input key", key) ``` -------------------------------- ### Install cryptography with pip Source: https://cryptography.io/en/latest/_sources/index.rst.txt Install the cryptography library using pip. ```console $ pip install cryptography ``` -------------------------------- ### X963KDF Derivation and Verification Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to derive a key using X963KDF and then verify its correctness. Ensure the same algorithm, length, and sharedinfo are used for both derivation and verification. This example uses SHA256 for hashing. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF sharedinfo = b"ANSI X9.63 Example" xkdf = X963KDF( algorithm=hashes.SHA256(), length=32, sharedinfo=sharedinfo, ) key = xkdf.derive(b"input key") xkdf = X963KDF( algorithm=hashes.SHA256(), length=32, sharedinfo=sharedinfo, ) xkdf.verify(b"input key", key) ``` -------------------------------- ### AES-SIV Doctest Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/aead.rst.txt Example demonstrating the usage of AES-SIV, likely for authenticated encryption. This doctest requires the 'os' module. ```python >>> import os ``` -------------------------------- ### Setup PKCS7 Test Data Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/asymmetric/serialization.rst.txt Initializes private key and certificate byte strings for testing PKCS7 operations. ```python ca_key = b""" -----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgA8Zqz5vLeR0ePZUe jBfdyMmnnI4U5uAJApWTsMn/RuWhRANCAAQY/8+7+Tm49d3D7sBAiwZ1BqtPzdgs UiROH+AQRme1XxW5Yr07zwxvvhr3tKEPtLnLboazUPlsUb/Bgte+xfkF -----END PRIVATE KEY----- """.strip() ca_cert = b""" -----BEGIN CERTIFICATE----- MIIBUTCB96ADAgECAgIDCTAKBggqhkjOPQQDAjAnMQswCQYDVQQGEwJVUzEYMBYG A1UEAwwPY3J5cHRvZ3JhcGh5IENBMB4XDTE3MDEwMTEyMDEwMFoXDTM4MTIzMTA4 MzAwMFowJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeSBDQTBZ MBMGByqGSM49AgEGCCqGSM49AwEHA0IABBj/z7v5Obj13cPuwECLBnUGq0/N2CxS JE4f4BBGZ7VfFblivTvPDG++Gve0oQ+0uctuhrNQ+WxRv8GC177F+QWjEzARMA8G GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhANES742XWm64tkGnz8Dn pG6u2lHkZFQr3oaVvPcemvlbAiEA0WGGzmYx5C9UvfXIK7NEziT4pQtyESE0uRVK Xw4nMqk= -----END CERTIFICATE----- """.strip() ca_cert_rsa = b""" -----BEGIN CERTIFICATE----- MIIExzCCAq+gAwIBAgIJAOcS06ClbtbJMA0GCSqGSIb3DQEBCwUAMBoxGDAWBgNV BAMMD2NyeXB0b2dyYXBoeSBDQTAeFw0yMDA5MTQyMTQwNDJaFw00ODAxMzEyMTQw NDJaMBoxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeSBDQTCCAiIwDQYJKoZIhvcNAQEB BQADggIPADCCAgoCggIBANBIheRc1HT4MzV5GvUbDk9CFU6DTomRApNqRmizriRq m6OY4Ht3d71BXog6/IBkqAnZ4/XJQ40G4sVDb52k11oPvfJ/F5pc+6UqPBL+QGzY ``` -------------------------------- ### C Style Guide: Parameter Spacing Source: https://cryptography.io/en/latest/development/c-bindings Illustrates the correct spacing after commas between parameters in C function declarations. ```c /* Good */ long f(int, char *) /* Bad */ long f(int,char *) ``` -------------------------------- ### Get Public Key Algorithm OID from CSR Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves the Object Identifier (OID) of the public key algorithm used in a CSR. This example shows how to get the OID for RSA encryption. ```python >>> csr.public_key_algorithm_oid ``` -------------------------------- ### Scrypt Key Derivation and Verification Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to initialize Scrypt with salt and parameters, derive a key from a password, and then verify that derived key against the same password. Ensure the KDF is re-initialized for verification if needed. ```python import os from cryptography.hazmat.primitives.kdf.scrypt import Scrypt salt = os.urandom(16) # derive kdf = Scrypt( salt=salt, length=32, n=2**14, r=8, p=1, ) key = kdf.derive(b"my great password") # verify kdf = Scrypt( salt=salt, length=32, n=2**14, r=8, p=1, ) kdf.verify(b"my great password", key) ``` -------------------------------- ### Get X.509 Certificate Version Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves the version of an X.509 certificate object. This example assumes `cert` is a loaded certificate object. ```python cert.version ``` -------------------------------- ### C Bindings: Conditional Compilation - Feature Exists Source: https://cryptography.io/en/latest/development/c-bindings Example of a C preprocessor directive to check for the existence of a function, starting a conditional block. ```c #ifdef QM_transmogrify ``` -------------------------------- ### Scrypt KDF Initialization and Usage Source: https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions Demonstrates how to initialize the Scrypt KDF with salt, length, and cost parameters, and then use it to derive and verify a key. ```APIDOC ## Class: cryptography.hazmat.primitives.kdf.scrypt.Scrypt ### Description Scrypt is a Key Derivation Function (KDF) designed for password storage, resistant to hardware-assisted attackers due to its tunable memory cost. It is described in RFC 7914 and conforms to the `KeyDerivationFunction` interface. ### Parameters * **salt** (_bytes_) – A salt. * **length** (_int_) – The desired length of the derived key in bytes. * **n** (_int_) – CPU/Memory cost parameter. Must be larger than 1 and a power of 2. * **r** (_int_) – Block size parameter. * **p** (_int_) – Parallelization parameter. ### Methods #### `derive(key_material)` ##### Description Generates and returns a new key from the supplied password. ##### Parameters * **key_material** (bytes-like) – The input key material. ##### Returns bytes: The derived key. ##### Raises * `TypeError`: If `key_material` is not `bytes`. * `cryptography.exceptions.AlreadyFinalized`: If called more than once. #### `derive_into(key_material, buffer)` ##### Description Generates a new key from the supplied password and writes it into the provided buffer. This is useful for avoiding new memory allocations. ##### Parameters * **key_material** (bytes-like) – The input key material. * **buffer** (bytes-like) – A writable buffer to write the derived key into. Must be equal to the length supplied in the constructor. ##### Returns int: The number of bytes written to the buffer. ##### Raises * `ValueError`: If the buffer length does not match the specified `length`. * `TypeError`: If `key_material` or `buffer` is not `bytes`. * `cryptography.exceptions.AlreadyFinalized`: If called more than once. #### `verify(key_material, expected_key)` ##### Description Checks if deriving a new key from the supplied `key_material` generates the same key as `expected_key`. Raises an exception if they do not match. Useful for verifying user-provided passwords against stored derived keys. ##### Parameters * **key_material** (_bytes_) – The input key material. * **expected_key** (_bytes_) – The expected result of deriving a new key. ##### Raises * `cryptography.exceptions.InvalidKey`: If the derived key does not match the expected key. * `cryptography.exceptions.AlreadyFinalized`: If called more than once. ### Raises * `cryptography.exceptions.UnsupportedAlgorithm`: If Scrypt is not supported by the OpenSSL version. * `TypeError`: If `salt` is not `bytes`. * `ValueError`: If `n` is less than 2, `n` is not a power of 2, `r` is less than 1, or `p` is less than 1. ``` -------------------------------- ### Get Signature Hash Algorithm from CSR Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves the hash algorithm used for signing a CSR. This example demonstrates checking if the algorithm is SHA256. ```python >>> from cryptography.hazmat.primitives import hashes >>> isinstance(csr.signature_hash_algorithm, hashes.SHA256) True ``` -------------------------------- ### Basic Certificate Builder Setup Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Initialize a CertificateBuilder with necessary imports and generate an RSA private key for signing. Note that all builder methods return a new instance. ```python >>> from cryptography import x509 >>> from cryptography.hazmat.primitives import hashes >>> from cryptography.hazmat.primitives.asymmetric import rsa >>> from cryptography.x509.oid import NameOID >>> import datetime >>> one_day = datetime.timedelta(1, 0, 0) >>> private_key = rsa.generate_private_key( ... public_exponent=65537, ... key_size=2048, ... ) >>> public_key = private_key.public_key() ``` -------------------------------- ### Get Signature Algorithm OID from CSR Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves the Object Identifier (OID) of the signature algorithm used to sign a CSR. This example shows the OID for sha256WithRSAEncryption. ```python >>> csr.signature_algorithm_oid ``` -------------------------------- ### Build Documentation with Nox Source: https://cryptography.io/en/latest/development/getting-started Run 'nox -e docs' to build the project's documentation. Ensure 'libenchant' is installed on non-Windows platforms before running this command. ```bash nox -e docs ``` -------------------------------- ### Get Public Key from CSR Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves the public key associated with a Certificate Signing Request (CSR). This example demonstrates checking if the public key is an RSAPublicKey. ```python >>> from cryptography.hazmat.primitives.asymmetric import rsa >>> public_key = csr.public_key() >>> isinstance(public_key, rsa.RSAPublicKey) True ``` -------------------------------- ### HKDF Initialization and Key Derivation Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to initialize an HKDF object with a specific algorithm, length, salt, and info, and then derive a key from input material. The same HKDF object can be re-initialized to verify the derived key. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF salt = os.urandom(16) info = b"hkdf-example" hkdf = HKDF( algorithm=hashes.SHA256(), length=32, salt=salt, info=info, ) key = hkdf.derive(b"input key") hkdf = HKDF( algorithm=hashes.SHA256(), length=32, salt=salt, info=info, ) hkdf.verify(b"input key", key) ``` -------------------------------- ### Get Naïve Certificate Not Valid Before Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves a naïve datetime object representing the start of the certificate's validity period in UTC. This property is deprecated; use `not_valid_before_utc` instead. ```python >>> cert.not_valid_before datetime.datetime(2010, 1, 1, 8, 30) ``` -------------------------------- ### Get Timezone-Aware Certificate Not Valid Before Source: https://cryptography.io/en/latest/_sources/x509/reference.rst.txt Retrieves a timezone-aware datetime object representing the start of the certificate's validity period in UTC. This is the recommended property to use for accurate time comparisons. ```python >>> cert.not_valid_before_utc datetime.datetime(2010, 1, 1, 8, 30, tzinfo=datetime.timezone.utc) ``` -------------------------------- ### Build Documentation Source: https://cryptography.io/en/latest/_sources/development/getting-started.rst.txt Generate project documentation using nox. ```console $ nox -e docs ``` -------------------------------- ### Install cryptography on Windows (compiled) Source: https://cryptography.io/en/latest/_sources/installation.rst.txt When compiling cryptography on Windows, set the OPENSSL_DIR environment variable to the location of your OpenSSL installation before running pip install. ```console C:\> \path\to\vcvarsall.bat x86_amd64 C:\> set OPENSSL_DIR=C:\OpenSSL-win64 C:\> pip install cryptography ``` -------------------------------- ### Initialize and Verify TOTP Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/twofactor.rst.txt Demonstrates creating a TOTP instance with a random key and verifying a generated token. ```python >>> import os >>> import time >>> from cryptography.hazmat.primitives.twofactor.totp import TOTP >>> from cryptography.hazmat.primitives.hashes import SHA1 >>> key = os.urandom(20) >>> totp = TOTP(key, 8, SHA1(), 30) >>> time_value = time.time() >>> totp_value = totp.generate(time_value) >>> totp.verify(totp_value, time_value) ``` -------------------------------- ### Build and Use a Server Verifier Source: https://cryptography.io/en/latest/x509/verification Demonstrates how to build a `ServerVerifier` using a `Store` populated with root certificates from `certifi` and a specific verification time. This verifier is then used to validate a server certificate against a specified DNS name. ```python >>> from cryptography.x509 import Certificate, DNSName, load_pem_x509_certificates >>> from cryptography.x509.verification import PolicyBuilder, Store >>> import certifi >>> from datetime import datetime, timezone >>> with open(certifi.where(), "rb") as pems: ... store = Store(load_pem_x509_certificates(pems.read())) >>> builder = PolicyBuilder().store(store) >>> # See the documentation on `time` below for more details. If >>> # significant time passes between creating a verifier and performing a >>> # verification, you may encounter issues with certificate expiration. >>> verification_time = datetime.now(timezone.utc) >>> builder = builder.time(verification_time) >>> verifier = builder.build_server_verifier(DNSName("cryptography.io")) >>> # NOTE: peer and untrusted_intermediates are Certificate and >>> # list[Certificate] respectively, and should be loaded from the >>> # application context that needs them verified, such as a >>> # TLS socket. >>> chain = verifier.verify(peer, untrusted_intermediates) ``` -------------------------------- ### HPKE Encryption and Decryption Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/hpke.rst.txt Demonstrates how to set up an HPKE suite, generate recipient keys, encrypt a message, and then decrypt it. Ensure the 'info' parameter matches for both encryption and decryption. ```python from cryptography.hazmat.primitives.hpke import Suite, KEM, KDF, AEAD from cryptography.hazmat.primitives.asymmetric import x25519 suite = Suite(KEM.X25519, KDF.HKDF_SHA256, AEAD.AES_128_GCM) # Generate recipient key pair private_key = x25519.X25519PrivateKey.generate() public_key = private_key.public_key() # Encrypt ciphertext = suite.encrypt(b"secret message", public_key, info=b"app info") # Decrypt plaintext = suite.decrypt(ciphertext, private_key, info=b"app info") ``` -------------------------------- ### KBKDFCMAC Initialization and Key Derivation Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to initialize and use KBKDFCMAC for deriving a new key. Ensure the input key material is of the correct length as specified by the algorithm. ```python from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.kdf.kbkdf import ( CounterLocation, KBKDFCMAC, Mode ) label = b"KBKDF CMAC Label" context = b"KBKDF CMAC Context" kdf = KBKDFCMAC( algorithm=algorithms.AES, mode=Mode.CounterMode, length=32, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, fixed=None, ) key = kdf.derive(b"32 bytes long input key material") ``` -------------------------------- ### Install Cryptography with OpenSSL and Rust on macOS (Homebrew) Source: https://cryptography.io/en/latest/installation Dynamically link cryptography with OpenSSL and Rust using Homebrew. Ensure you have OpenSSL 3 and Rust installed before proceeding with the pip install. ```bash $ brew install openssl@3 rust $ pip install --no-binary cryptography cryptography ``` -------------------------------- ### Deriving and Verifying a Key with X963KDF Source: https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions Demonstrates how to instantiate X963KDF, derive a key from input material, and then verify that derived key. Ensure the same algorithm, length, and sharedinfo are used for both derivation and verification. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF sharedinfo = b"ANSI X9.63 Example" xkdf = X963KDF( algorithm=hashes.SHA256(), length=32, sharedinfo=sharedinfo, ) key = xkdf.derive(b"input key") xkdf = X963KDF( algorithm=hashes.SHA256(), length=32, sharedinfo=sharedinfo, ) xkdf.verify(b"input key", key) ``` -------------------------------- ### OpenSSH Private Key Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/asymmetric/serialization.rst.txt Example of an ECDSA private key in OpenSSH format. ```text -----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS 1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRI0fWnI1CxX7qYqp0ih6bxjhGmUrZK /Axf8vhM8Db3oH7CFR+JdL715lUdu4XCWvQZKVf60/h3kBFhuxQC23XjAAAAqKPzVaOj81 WjAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEjR9acjULFfupiq nSKHpvGOEaZStkr8DF/y+EzwNvegfsIVH4l0vvXmVR27hcJa9BkpV/rT+HeQEWG7FALbde MAAAAga/VGV2asRlL3kXXao0aochQ59nXHA2xEGeAoQd952r0AAAAJbWFya29AdmZmAQID BAUGBw== -----END OPENSSH PRIVATE KEY----- ``` -------------------------------- ### X963KDF Constructor and Usage Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to instantiate and use the X963KDF for key derivation and verification. ```APIDOC ## X963KDF ### Description X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSI in the `ANSI X9.63:2001` document, to be used to derive keys for use after a Key Exchange negotiation operation. SECG in `SEC 1 v2.0` recommends that :class:`~cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash` be used for new projects. This KDF should only be used for backwards compatibility with pre-existing protocols. **Warning**: X963KDF should not be used for password storage. ### Class Definition ```python class X963KDF(algorithm, length, sharedinfo) ``` ### Parameters - **algorithm**: An instance of :class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm`. - **length** (int): The desired length of the derived key in bytes. Maximum is ``hashlen * (2^32 -1)``. - **sharedinfo** (bytes): Application specific context information. If ``None`` is explicitly passed an empty byte string will be used. ### Raises - **TypeError**: This exception is raised if ``sharedinfo`` is not ``bytes``. ### Method: derive ```python derive(key_material) ``` Derives a new key from the input key material. #### Parameters - **key_material** (:term:`bytes-like`): The input key material. #### Returns - bytes: The derived key. #### Raises - **TypeError**: This exception is raised if ``key_material`` is not ``bytes``. - **cryptography.exceptions.AlreadyFinalized**: This is raised when :meth:`derive`, :meth:`derive_into`, or :meth:`verify` is called more than once. ### Method: derive_into ```python derive_into(key_material, buffer) ``` #### Parameters - **key_material** (:term:`bytes-like`): The input key material. - **buffer** (writable buffer): A writable buffer to write the derived key into. ### Method: verify ```python verify(key_material, expected_key) ``` This checks whether deriving a new key from the supplied ``key_material`` generates the same key as the ``expected_key``, and raises an exception if they do not match. #### Parameters - **key_material** (bytes): The input key material. This is the same as ``key_material`` in :meth:`derive`. - **expected_key** (bytes): The expected result of deriving a new key, this is the same as the return value of :meth:`derive`. #### Raises - **cryptography.exceptions.InvalidKey**: This is raised when the derived key does not match the expected key. - **cryptography.exceptions.AlreadyFinalized**: This is raised when :meth:`derive`, :meth:`derive_into`, or :meth:`verify` is called more than once. ### Example Usage ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF sharedinfo = b"ANSI X9.63 Example" xkdf = X963KDF( algorithm=hashes.SHA256(), length=32, sharedinfo=sharedinfo, ) key = xkdf.derive(b"input key") xkdf = X963KDF( algorithm=hashes.SHA256(), length=32, sharedinfo=sharedinfo, ) xkdf.verify(b"input key", key) ``` ``` -------------------------------- ### OpenSSH Public Key Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/asymmetric/serialization.rst.txt Example of an RSA public key in OpenSSH format. ```text ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDu/XRP1kyK6Cgt36gts9XAk FiiuJLW6RU0j3KKVZSs1I7Z3UmU9/9aVh/rZV43WQG8jaR6kkcP4stOR0DEtll PDA7ZRBnrfiHpSQYQ874AZaAoIjgkv7DBfsE6gcDQLub0PFjWyrYQUJhtOLQEK vY/G0vt2iRL3juawWmCFdTK3W3XvwAdgGk71i6lHt+deOPNEPN2H58E4odrZ2f sxn/adpDqfb2sM0kPwQs0aWvrrKGvUaustkivQE4XWiSFnB0oJB/lKK/CKVKuy ///ImSCGHQRvhwariN2tvZ6CBNSLh3iQgeB0AkyJlng7MXB2qYq/Ci2FUOryCX 2MzHvnbv testkey@localhost ``` -------------------------------- ### Verify Cryptography Version Source: https://cryptography.io/en/latest/doing-a-release After installation, verify the installed version of cryptography and cryptography-vectors. Ensure these match the newly released versions. ```python >>> import cryptography >>> cryptography.__version__ '...' >>> import cryptography_vectors >>> cryptography_vectors.__version__ '...' ``` -------------------------------- ### Using HKDFExpand for Key Derivation Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to use HKDFExpand to derive a key from provided material. It shows both deriving a key and verifying it against the original material. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand info = b"hkdf-example" key_material = os.urandom(16) hkdf = HKDFExpand( algorithm=hashes.SHA256(), length=32, info=info, ) key = hkdf.derive(key_material) hkdf = HKDFExpand( algorithm=hashes.SHA256(), length=32, info=info, ) hkdf.verify(key_material, key) ``` -------------------------------- ### ConcatKDFHash Example Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/key-derivation-functions.rst.txt Demonstrates how to use ConcatKDFHash to derive a key from input material and then verify it. Ensure the same algorithm, length, and otherinfo are used for both derivation and verification. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash otherinfo = b"concatkdf-example" ckdf = ConcatKDFHash( algorithm=hashes.SHA256(), length=32, otherinfo=otherinfo, ) key = ckdf.derive(b"input key") ckdf = ConcatKDFHash( algorithm=hashes.SHA256(), length=32, otherinfo=otherinfo, ) ckdf.verify(b"input key", key) ``` -------------------------------- ### Install Cryptography using pip Source: https://cryptography.io/en/latest/installation Use this command to install the cryptography library with pip. Ensure your pip is up-to-date for the best experience. ```bash $ pip install cryptography ``` -------------------------------- ### Upgrade pip for cryptography installation Source: https://cryptography.io/en/latest/_sources/faq.rst.txt Before installing cryptography, upgrade pip to the latest version. Use the appropriate command for your operating system. ```bash pip install -U pip ``` ```bash python -m pip install -U pip ``` -------------------------------- ### Generate and Load X448 Private Key Source: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/x448 Demonstrates generating an X448 private key and then loading it back from its raw byte representation. Requires importing serialization and x448 modules. ```python from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import x448 private_key = x448.X448PrivateKey.generate() private_bytes = private_key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption() ) loaded_private_key = x448.X448PrivateKey.from_private_bytes(private_bytes) ``` -------------------------------- ### Build Cryptography with Dynamic OpenSSL via Homebrew (macOS) Source: https://cryptography.io/en/latest/_sources/installation.rst.txt Installs OpenSSL 3 and Rust using Homebrew, then installs cryptography dynamically linking against OpenSSL. ```console $ brew install openssl@3 rust $ pip install --no-binary cryptography cryptography ``` -------------------------------- ### Install build dependencies on Debian/Ubuntu Source: https://cryptography.io/en/latest/_sources/installation.rst.txt On Debian/Ubuntu systems, install essential build tools such as build-essential, OpenSSL development headers, Python development headers, and Cargo. ```console $ sudo apt-get install build-essential libssl-dev libffi-dev \ python3-dev cargo pkg-config ``` -------------------------------- ### ConcatKDFHMAC Key Derivation Example Source: https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions Shows how to derive and verify a key using ConcatKDFHMAC with a salt. Using a salt is highly recommended for randomizing the KDF's output. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC salt = os.urandom(16) otherinfo = b"concatkdf-example" ckdf = ConcatKDFHMAC( algorithm=hashes.SHA256(), length=32, salt=salt, otherinfo=otherinfo, ) key = ckdf.derive(b"input key") ckdf = ConcatKDFHMAC( algorithm=hashes.SHA256(), length=32, salt=salt, otherinfo=otherinfo, ) ckdf.verify(b"input key", key) ``` -------------------------------- ### Install build dependencies on Debian/Ubuntu Source: https://cryptography.io/en/latest/installation Installs essential build tools and development headers for cryptography on Debian and Ubuntu systems. This includes build-essential, OpenSSL, and Python development files. ```bash $ sudo apt-get install build-essential libssl-dev libffi-dev \ python3-dev cargo pkg-config ``` -------------------------------- ### AESSIV Encryption and Decryption Example Source: https://cryptography.io/en/latest/hazmat/primitives/aead Demonstrates how to generate a key, encrypt data with associated data (including a nonce), and then decrypt it using AESSIV. Ensure the key is kept secret and nonces have sufficient entropy. ```python import os from cryptography.hazmat.primitives.ciphers.aead import AESSIV data = b"a secret message" nonce = os.urandom(16) aad = [b"authenticated but unencrypted data", nonce] key = AESSIV.generate_key(bit_length=512) # AES256 requires 512-bit keys for SIV aessiv = AESSIV(key) ct = aessiv.encrypt(data, aad) aessiv.decrypt(ct, aad) ``` -------------------------------- ### Generate and Load X448 Public Key Source: https://cryptography.io/en/latest/_sources/hazmat/primitives/asymmetric/x448.rst.txt Demonstrates generating an X448 private key, deriving its public key, serializing the public key to raw bytes, and then deserializing it back into an X448PublicKey object. Ensure the cryptography library is installed. ```python from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import x448 private_key = x448.X448PrivateKey.generate() public_key = private_key.public_key() public_bytes = public_key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw ) loaded_public_key = x448.X448PublicKey.from_public_bytes(public_bytes) ``` -------------------------------- ### Install Cryptography with Custom OpenSSL Path Source: https://cryptography.io/en/latest/_sources/installation.rst.txt Use this command to install the cryptography library when you need to specify a custom OpenSSL directory, such as for static builds or alternative SSL implementations. ```bash $ env OPENSSL_STATIC=1 OPENSSL_DIR="/opt/local" pip install --no-binary cryptography cryptography ``` -------------------------------- ### Install build dependencies on Fedora/RHEL/CentOS Source: https://cryptography.io/en/latest/_sources/installation.rst.txt For Fedora, RHEL, and CentOS, install development packages including GCC, libffi, Python development headers, OpenSSL development files, and Cargo. ```console $ sudo dnf install redhat-rpm-config gcc libffi-devel python3-devel \ openssl-devel cargo pkg-config ``` -------------------------------- ### Deriving and Verifying a Key with KBKDFHMAC Source: https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions Demonstrates how to instantiate KBKDFHMAC with SHA256, CounterMode, and specific parameters, derive a key from input material, and then verify the derived key. ```python import os from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.kbkdf import ( CounterLocation, KBKDFHMAC, Mode ) label = b"KBKDF HMAC Label" context = b"KBKDF HMAC Context" kdf = KBKDFHMAC( algorithm=hashes.SHA256(), mode=Mode.CounterMode, length=32, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, fixed=None, ) key = kdf.derive(b"input key") kdf = KBKDFHMAC( algorithm=hashes.SHA256(), mode=Mode.CounterMode, length=32, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, fixed=None, ) kdf.verify(b"input key", key) ``` -------------------------------- ### Install build dependencies on Alpine Linux Source: https://cryptography.io/en/latest/_sources/installation.rst.txt On Alpine Linux, install necessary build tools including GCC, Python headers, OpenSSL development files, and Cargo for Rust. ```console $ sudo apk add gcc musl-dev python3-dev libffi-dev openssl-dev cargo pkgconfig ``` -------------------------------- ### HMAC Initialization and Usage Source: https://cryptography.io/en/latest/hazmat/primitives/mac/hmac Demonstrates how to initialize an HMAC object with a key and hash algorithm, update it with a message, and finalize it to get the signature. ```APIDOC ## HMAC Class ### Description HMAC objects take a `key` and a `HashAlgorithm` instance. The `key` should be randomly generated bytes and is recommended to be equal in length to the `digest_size` of the hash function chosen. You must keep the `key` secret. This is an implementation of **RFC 2104**. ### Method `cryptography.hazmat.primitives.hmac.HMAC(_key_, _algorithm_) ### Parameters #### Parameters - **key** (bytes-like) – The secret key. - **algorithm** – An `HashAlgorithm` instance such as those described in Cryptographic Hashes. ### Raises - **cryptography.exceptions.UnsupportedAlgorithm** – This is raised if the provided `algorithm` isn’t supported. ### Example ```python >>> from cryptography.hazmat.primitives import hashes, hmac >>> key = b'test key. Beware! A real key should use os.urandom or TRNG to generate' >>> h = hmac.HMAC(key, hashes.SHA256()) >>> h.update(b"message to hash") >>> signature = h.finalize() >>> signature b'k\xd9\xb29\xefS\xf8\xcf\xec\xed\xbf\x95\xe6\x97X\x18\x9e%\x11DU1\x9fq}\x9a\x9c\xe0)y`=' ``` ``` -------------------------------- ### Example PEM file for RSA Public Key Source: https://cryptography.io/en/latest/_sources/faq.rst.txt This is an example of a PEM-encoded RSA Public Key file. Ensure your PEM files have a correct header, footer, and line formatting. ```text -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7CsKFSzq20NLb2VQDXma 9DsDXtKADv0ziI5hT1KG6Bex5seE9pUoEcUxNv4uXo2jzAUgyRweRl/DLU8SoN8+ WWd6YWik4GZvNv7j0z28h9Q5jRySxy4dmElFtIRHGiKhqd1Z06z4AzrmKEzgxkOk LJjY9cvwD+iXjpK2oJwNNyavvjb5YZq6V60RhpyNtKpMh2+zRLgIk9sROEPQeYfK 22zj2CnGBMg5Gm2uPOsGDltl/I/Fdh1aO3X4i1GXwCuPf1kSAg6lPJD0batftkSG v0X0heUaV0j1HSNlBWamT4IR9+iJfKJHekOqvHQBcaCu7Ja4kXzx6GZ3M2j/Ja3A 2QIDAQAB -----END PUBLIC KEY----- ``` -------------------------------- ### C Bindings: Defining Constants Source: https://cryptography.io/en/latest/development/c-bindings Shows how to define C constants with appropriate types, matching values set by '#define'. ```c #define SOME_INTEGER_LITERAL 0x0; #define SOME_UNSIGNED_INTEGER_LITERAL 0x0001U; #define SOME_STRING_LITERAL "hello"; ``` ```c static const int SOME_INTEGER_LITERAL; static const unsigned int SOME_UNSIGNED_INTEGER_LITERAL; static const char *const SOME_STRING_LITERAL; ```