Skip to main content

hash, hmac, RSA, ECC, X.509, TLS, DTLS, handshakes, and secrets with an mbed TLS back end

Project description

https://circleci.com/gh/Synss/python-mbedtls/tree/master.svg?style=svg https://github.com/Synss/python-mbedtls/actions/workflows/main.yml/badge.svg?branch=master https://coveralls.io/repos/github/Synss/python-mbedtls/badge.svg?branch=master

python-mbedtls is a free cryptographic library for Python that uses mbed TLS for back end.

mbed TLS (formerly known as PolarSSL) makes it trivially easy for developers to include cryptographic and SSL/TLS capabilities in their (embedded) products, facilitating this functionality with a minimal coding footprint.

python-mbedtls API follows the recommendations from:

  • PEP 272 – API for Block Encryption Algorithms v1.0

  • PEP 452 – API for Cryptographic Hash Functions v2.0

  • PEP 506 – Adding a Secret Module to the Standard Library

  • PEP 543 – A Unified TLS API for Python

and therefore plays well with the cryptographic services from the Python standard library and many other cryptography libraries as well.

License

python-mbedtls is licensed under the MIT License (see LICENSE.txt). This enables the use of python-mbedtls in both open source and closed source projects. The MIT License is compatible with both GPL and Apache 2.0 license under which mbed TLS is distributed.

API documentation

https://synss.github.io/python-mbedtls/

Installation

The bindings are tested with mbedTLS 2.28.0 for Python 3.7, 3.8, 3.9, and 3.10 on Linux, macOS, and Windows.

manylinux wheels are available for 64-bit Linux systems. Install with pip install python-mbedtls.

Usage and examples

Now, let us see examples using the various parts of the library.

Check which version of mbed TLS is being used by python-mbedtls

The mbedtls.version module shows the run-time version information to mbed TLS.

>>> from mbedtls import version
>>> _ = version.version  # "mbed TLS 2.28.0"
>>> _ = version.version_info  # (2, 28, 0)

Message digest

The mbedtls.hashlib module supports MD2, MD4, MD5, SHA-1, SHA-2 (in 224, 256, 384, and 512-bits), and RIPEMD-160 secure hashes and message digests. Note that MD2 and MD4 are not included by default and are only present if they are compiled in mbedtls.

Here are the examples from (standard) hashlib ported to python-mbedtls:

>>> from mbedtls import hashlib
>>> m = hashlib.md5()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
>>> m.digest_size
16
>>> m.block_size
64

More condensed:

>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

Using new():

>>> h = hashlib.new('ripemd160')
>>> h.update(b"Nobody inspects the spammish repetition")
>>> h.hexdigest()
'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc'

HMAC algorithm

The mbedtls.hmac module computes HMAC.

Example:

>>> from mbedtls import hmac
>>> m = hmac.new(b"This is my secret key", digestmod="md5")
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\x9d-/rj\\\x98\x80\xb1rG\x87\x0f\xe9\xe4\xeb'

Warning:

The message is cleared after calculation of the digest. Only call mbedtls.hmac.Hmac.digest() or mbedtls.hmac.Hmac.hexdigest() once per message.

HMAC-based key derivation function (HKDF)

The mbedtls.hkdf module exposes extract-and-expand key derivation functions. The main function is hkdf() but extract() and expand() may be used as well.

Example:

>>> from mbedtls import hkdf
>>> hkdf.hkdf(
...     b"my secret key",
...     length=42,
...     info=b"my cool app",
...     salt=b"and pepper",
...     digestmod=hmac.sha256
... )
b'v,\xef\x90\xccU\x1d\x1b\xd7\\a\xaf\x92\xac\n\x90\xf9q\xf4)\xcd"\xf7\x1a\x94p\x03.\xa8e\x1e\xfb\x92\xe8l\x0cc\xf8e\rvj'

where info, salt, and digestmod are optional, although providing (at least) info is highly recommended.

Symmetric cipher

The mbedtls.cipher module provides symmetric encryption. The API follows the recommendations from PEP 272 so that it can be used as a drop-in replacement to other libraries.

python-mbedtls provides the following algorithms:

  • AES encryption/decryption (128, 192, and 256 bits) in ECB, CBC, CFB128, CTR, OFB, or XTS mode;

  • AES AEAD (128, 192, and 256 bits) in GCM or CCM mode;

  • ARC4 encryption/decryption;

  • ARIA encryption/decryption (128, 192, and 256 bits) in ECB, CBC, CTR, or GCM modes;

  • Blowfish encryption/decryption in ECB, CBC, CFB64, or CTR mode;

  • Camellia encryption/decryption (128, 192, and 256 bits) in ECB, CBC, CFB128, CTR, or GCM mode;

  • DES, DES3, and double DES3 encryption/decryption in ECB or CBC mode;

  • CHACHA20 and CHACHA20/POLY1305 encryption/decryption.

Example:

>>> from mbedtls import cipher
>>> c = cipher.AES.new(b"My 16-bytes key.", cipher.MODE_CBC, b"CBC needs an IV.")
>>> enc = c.encrypt(b"This is a super-secret message!!")
>>> enc
b"*`k6\x98\x97=[\xdf\x7f\x88\x96\xf5\t\x19J\xf62h\xf4n\xca\xe8\xfe\xf5\xd7X'\xb1\x8c\xc9\x85"
>>> c.decrypt(enc)
b'This is a super-secret message!!'

RSA public key

The mbedtls.pk module provides the RSA cryptosystem. This includes:

  • Public-private key generation and key import/export in PEM and DER formats;

  • asymmetric encryption and decryption;

  • message signature and verification.

Key generation, the default size is 2048 bits:

>>> from mbedtls import pk
>>> rsa = pk.RSA()
>>> prv = rsa.generate()
>>> rsa.key_size
256

Message encryption and decryption:

>>> enc = rsa.encrypt(b"secret message")
>>> rsa.decrypt(enc)
b'secret message'

Message signature and verification:

>>> sig = rsa.sign(b"Please sign here.")
>>> rsa.verify(b"Please sign here.", sig)
True
>>> rsa.verify(b"Sorry, wrong message.", sig)
False
>>> pub = rsa.export_public_key(format="DER")
>>> other = pk.RSA.from_buffer(pub)
>>> other.verify(b"Please sign here.", sig)
True

Static and ephemeral elliptic curve Diffie-Hellman

The mbedtls.pk module provides the ECC cryptosystem. This includes:

  • Public-private key generation and key import/export in the PEM and DER formats;

  • asymmetric encrypt and decryption;

  • message signature and verification;

  • ephemeral ECDH key exchange.

get_supported_curves() returns the list of supported curves.

The API of the ECC class is the same as the API of the RSA class but ciphering (encrypt() and decrypt() is not supported by Mbed TLS).

Message signature and verification using elliptic a curve digital signature algorithm (ECDSA):

>>> from mbedtls import pk
>>> ecdsa = pk.ECC()
>>> prv = ecdsa.generate()
>>> sig = ecdsa.sign(b"Please sign here.")
>>> ecdsa.verify(b"Please sign here.", sig)
True
>>> ecdsa.verify(b"Sorry, wrong message.", sig)
False
>>> pub = ecdsa.export_public_key(format="DER")
>>> other = pk.ECC.from_buffer(pub)
>>> other.verify(b"Please sign here.", sig)
True

The classes ECDHServer and ECDHClient may be used for ephemeral ECDH. The key exchange is as follows:

>>> ecdh_srv = pk.ECDHServer()
>>> ecdh_cli = pk.ECDHClient()

The server generates the ServerKeyExchange encrypted payload and passes it to the client:

>>> ske = ecdh_srv.generate()
>>> ecdh_cli.import_SKE(ske)

then the client generates the ClientKeyExchange encrypted payload and passes it back to the server:

>>> cke = ecdh_cli.generate()
>>> ecdh_srv.import_CKE(cke)

Now, client and server may generate their shared secret:

>>> secret = ecdh_srv.generate_secret()
>>> ecdh_cli.generate_secret() == secret
True
>>> ecdh_srv.shared_secret == ecdh_cli.shared_secret
True

Diffie-Hellman-Merkle key exchange

The classes DHServer and DHClient may be used for DH Key exchange. The classes have the same API as ECDHServer and ECDHClient, respectively.

The key exchange is as follow:

>>> from mbedtls.mpi import MPI
>>> from mbedtls import pk
>>> dh_srv = pk.DHServer(MPI.prime(128), MPI.prime(96))
>>> dh_cli = pk.DHClient(MPI.prime(128), MPI.prime(96))

The 128-bytes prime and the 96-bytes prime are the modulus P and the generator G.

The server generates the ServerKeyExchange payload:

>>> ske = dh_srv.generate()
>>> dh_cli.import_SKE(ske)

The payload ends with G^X mod P where X is the secret value of the server.

>>> cke = dh_cli.generate()
>>> dh_srv.import_CKE(cke)

cke is G^Y mod P (with Y the secret value from the client) returned as its representation in bytes so that it can be readily transported over the network.

As in ECDH, client and server may now generate their shared secret:

>>> secret = dh_srv.generate_secret()
>>> dh_cli.generate_secret() == secret
True
>>> dh_srv.shared_secret == dh_cli.shared_secret
True

X.509 certificate writing and parsing

The mbedtls.x509 module can be used to parse X.509 certificates or create and verify a certificate chain.

Here, the trusted root is a self-signed CA certificate ca0_crt signed by ca0_key.

>>> import datetime as dt
>>>
>>> from mbedtls import hashlib
>>> from mbedtls import pk
>>> from mbedtls import x509
>>>
>>> now = dt.datetime.utcnow()
>>> ca0_key = pk.RSA()
>>> _ = ca0_key.generate()
>>> ca0_csr = x509.CSR.new(ca0_key, "CN=Trusted CA", hashlib.sha256())
>>> ca0_crt = x509.CRT.selfsign(
...     ca0_csr, ca0_key,
...     not_before=now, not_after=now + dt.timedelta(days=90),
...     serial_number=0x123456,
...     basic_constraints=x509.BasicConstraints(True, 1))
...

An intermediate then issues a Certificate Singing Request (CSR) that the root CA signs:

>>> ca1_key = pk.ECC()
>>> _ = ca1_key.generate()
>>> ca1_csr = x509.CSR.new(ca1_key, "CN=Intermediate CA", hashlib.sha256())
>>>
>>> ca1_crt = ca0_crt.sign(
...     ca1_csr, ca0_key, now, now + dt.timedelta(days=90), 0x123456,
...     basic_constraints=x509.BasicConstraints(ca=True, max_path_length=3))
...

And finally, the intermediate CA signs a certificate for the End Entity on the basis of a new CSR:

>>> ee0_key = pk.ECC()
>>> _ = ee0_key.generate()
>>> ee0_csr = x509.CSR.new(ee0_key, "CN=End Entity", hashlib.sha256())
>>>
>>> ee0_crt = ca1_crt.sign(
...     ee0_csr, ca1_key, now, now + dt.timedelta(days=90), 0x987654)
...

The emitting certificate can be used to verify the next certificate in the chain:

>>> ca1_crt.verify(ee0_crt)
True
>>> ca0_crt.verify(ca1_crt)
True

Note, however, that this verification is only one step in a private key infrastructure and does not take CRLs, path length, etc. into account.

TLS client and server

The mbedtls.tls module provides TLS clients and servers. The API follows the recommendations of PEP 543. Note, however, that the Python standard SSL library does not follow the PEP so that this library may not be a drop-in replacement.

See examples in the programs/ directory of the repository and tests/test_tls.py.

DTLS client and server

The mbedtls.tls module further provides DTLS (encrypted UDP traffic). Client and server must be bound and connected for the handshake so that DTLS should use recv() and send() as well.

See examples in the programs/ directory of the repository and tests/test_tls.py.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-mbedtls-2.1.0.tar.gz (122.8 kB view details)

Uploaded Source

Built Distributions

python_mbedtls-2.1.0-cp310-cp310-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.10 Windows x86-64

python_mbedtls-2.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.6 MB view details)

Uploaded CPython 3.10 manylinux: glibc 2.17+ x86-64

python_mbedtls-2.1.0-cp310-cp310-macosx_10_9_x86_64.whl (1.5 MB view details)

Uploaded CPython 3.10 macOS 10.9+ x86-64

python_mbedtls-2.1.0-cp39-cp39-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.9 Windows x86-64

python_mbedtls-2.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.6 MB view details)

Uploaded CPython 3.9 manylinux: glibc 2.17+ x86-64

python_mbedtls-2.1.0-cp39-cp39-macosx_10_9_x86_64.whl (1.5 MB view details)

Uploaded CPython 3.9 macOS 10.9+ x86-64

python_mbedtls-2.1.0-cp38-cp38-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.8 Windows x86-64

python_mbedtls-2.1.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.6 MB view details)

Uploaded CPython 3.8 manylinux: glibc 2.17+ x86-64

python_mbedtls-2.1.0-cp38-cp38-macosx_10_9_x86_64.whl (1.5 MB view details)

Uploaded CPython 3.8 macOS 10.9+ x86-64

python_mbedtls-2.1.0-cp37-cp37m-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.7m Windows x86-64

python_mbedtls-2.1.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.0 MB view details)

Uploaded CPython 3.7m manylinux: glibc 2.17+ x86-64

python_mbedtls-2.1.0-cp37-cp37m-macosx_10_9_x86_64.whl (1.5 MB view details)

Uploaded CPython 3.7m macOS 10.9+ x86-64

File details

Details for the file python-mbedtls-2.1.0.tar.gz.

File metadata

  • Download URL: python-mbedtls-2.1.0.tar.gz
  • Upload date:
  • Size: 122.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.9.12

File hashes

Hashes for python-mbedtls-2.1.0.tar.gz
Algorithm Hash digest
SHA256 44b28ce6f46204aef34a6af7df1d81c0751449015ce1281976e8703178d52631
MD5 8737a3deb079b5d9e69caa6639f05be1
BLAKE2b-256 e5d627f7e54701652a0011c45a062cfb5f4fc8740fd391b5b7e2fab670278f6a

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 5694fce176cc7c7f595c756380ad8ab19c12373c6c8c1599b746cee0a9137a77
MD5 8c23917cada2e1c928e1e8954a617274
BLAKE2b-256 986958b9fcb5d21f607db74ba0346835c693c4fd0f335c6d4281d24d688ef415

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 286502dd73ee4ed6a37b32b14284054c3e3979e05e44e69e6badd63d1d7e9bfa
MD5 8f383168ade1aa09934c642d4d668c25
BLAKE2b-256 828ec2e71b0c9bc8218aa0da5e26b78764e5ebaf5814e99c7a48ad210342364e

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp310-cp310-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp310-cp310-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 ad569fd4bd7fc8ce3c865d028042fa77b41153cac33299fa252816d53db50bf2
MD5 ca6be3a092ee2881c48252f9bf52e3d7
BLAKE2b-256 9b7f00c484a5c5e2712b5747d8574ff29d9c34e192a75d1932fba957e24ce644

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp39-cp39-win_amd64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 556a9259064e834e33a15c713c2edd1ac3ffca2b642b0e79f5b16fb6b1de4a78
MD5 4bb00914966c0fea91f858acf1ab113c
BLAKE2b-256 079910603757afe35560fe1070e55c4655a5f909e9ec1ff317716f7f7ab249f2

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 e53fb6a11d64d2fd4428a89be22166a2a34dc8186bd0d689973167e73742b9a6
MD5 aee7e402ae731931f8f76a27bc9927e2
BLAKE2b-256 5f1ba724ee1f60db7b6f7fe59cd0ccefe6ad38f49097e14732decda0778e8c92

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp39-cp39-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp39-cp39-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 8cfdf9bc1acc7784db92a79b0c1bbab057ed86a12db29c8ebc96beb675fde34a
MD5 35629d4445700828246fbba263378848
BLAKE2b-256 b219869438e0536b237ad1a1c1a8a5edeb048bceac030689b0e4a760f7b05b8c

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp38-cp38-win_amd64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 cc8758ef2487d29d51de675054eba6f67f8772baa1e30b7bdfdf025b6fe2239f
MD5 6f0165de7061c4ef048ba4faf422454b
BLAKE2b-256 256d268c88a3a1f9254d1b1e9da450039c07aaa6ffeb3c1400e580a6ea83a688

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 182ccd21db260476200ce22f08c80dc9f5e44003e01408a5a1c2cf4818cef02c
MD5 c46738557eb5059f7b4c2afd65113788
BLAKE2b-256 163edf70591b474b16969a2bbd7a754ae4f6a9c74c0e62b2a9d6099cf9244adb

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp38-cp38-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp38-cp38-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 c1c907cbd6d9d54943a912c45785abd3d4b7de4efb6d7adde33c707578b03c94
MD5 d15f7260822c390b41bfb5b68dda1911
BLAKE2b-256 8b5c7d9ef81995a7141aaa7995c39b44bc62b4034625f65f16f9ca1325d518f3

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp37-cp37m-win_amd64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp37-cp37m-win_amd64.whl
Algorithm Hash digest
SHA256 f332cda7c44b1eefa4fbf672b3dc5166f8b35a1825190a0230b7debd82f65756
MD5 1dc3b190ecffc9b270317c76aa4a5e0b
BLAKE2b-256 eaf3a5089725512fb2832a6f22a1a551cd99050f13504ea8a0dc6a44d6a9fb91

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 4a7d2cf8827be25d623cda9120418935a6250ca31bad432bad6e95f2d27ce7db
MD5 c9c81938a67c40e336d1aa8ef8dc5ee0
BLAKE2b-256 7fa2c3c3c5306685761dfd116b09608de631b0ca865a89fec5e9aec7c811db63

See more details on using hashes here.

File details

Details for the file python_mbedtls-2.1.0-cp37-cp37m-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for python_mbedtls-2.1.0-cp37-cp37m-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 32ea3ecc0e45e56356bea484c5d94069ee6c8eade31ab14a0f4306c502dfe876
MD5 6999daefba0fc2f22294d072abf6ccae
BLAKE2b-256 5d329583885e79a4b6206edc4cf0a7b15bd05b7c570a6c4cd9179a4c36ccbcbd

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page