Skip to main content

hash, hmac, RSA, and X.509 with an mbed TLS back end

Project description

https://circleci.com/gh/Synss/python-mbedtls/tree/develop.svg?style=svg https://coveralls.io/repos/github/Synss/python-mbedtls/badge.svg?branch=develop

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 452: API for Cryptographic Hash Functions v2.0 and PEP 272 API for Block Encryption Algorithms v1.0 and can therefore be used as a drop-in replacements to PyCrypto or Python’s hashlib and hmac

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.

Installation

The bindings are tested with Python 2.7, 3.4, 3.5, and 3.6.

mbedtls is available on Debian. Install with:

# apt-get install libmbedtls-dev
# apt-get install libpython-dev   # for Python 2, or
# apt-get install libpython3-dev  # for Python 3

and pyton-mbedtls:

$ python -m pip install python-mbedtls

Message digest with mbedtls.hash

The mbedtls.hash module provides MD5, SHA-1, SHA-2, and RIPEMD-160 secure hashes and message digests. The API follows the recommendations from PEP 452 so that it can be used as a drop-in replacement to e.g. hashlib or PyCrypto.

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

>>> from mbedtls import hash as 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 with mbedtls.hmac

The mbedtls.hmac module computes HMAC. The API follows the recommendations from PEP 452 as well.

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.

Symmetric cipher with mbedtls.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 e.g. PyCrypto.

mbedtls provides the following algorithms:

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

  • Arc4 encryption/decryption;

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

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

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

Notes:
  • Tagging and padding are not wrapped.

  • The counter in CTR mode cannot be explicitly provided.

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\x19J7\x93\xb5\xe0~\t\x9e\x968m\xcd\x9c3\x04o\xe6'
>>> c.decrypt(enc)
b'This is a super-secret message!'

RSA public key with mbedtls.pk

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—elliptic 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:

>>> srv = pk.ECDHServer()
>>> cli = pk.ECDHClient()

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

>>> ske = srv.generate()
>>> cli.import_SKE(ske)

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

>>> cke = cli.generate()
>>> srv.import_CKE(cke)

Now, client and server may generate their shared secret:

>>> secret = srv.generate_secret()
>>> cli.generate_secret() == secret
True
>>> srv.shared_secret == 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 import pk
>>> srv = pk.DHServer(23, 5)
>>> cli = pk.DHClient(23, 5)

The values 23 and 5 are the prime modulus (P) and the generator (G).

The server generates the ServerKeyExchange payload:

>>> ske = srv.generate()
>>> cli.import_SKE(ske)

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

>>> cke = cli.generate()
>>> 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 = srv.generate_secret()
>>> cli.generate_secret() == secret
True
>>> srv.shared_secret == cli.shared_secret
True

X.509 Certificate writing and parsing with mbedtls.x509

The 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 hash as 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, ca=True, max_path_length=-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,
...     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.

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-0.12.1.tar.gz (29.5 kB view details)

Uploaded Source

Built Distributions

File details

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

File metadata

  • Download URL: python-mbedtls-0.12.1.tar.gz
  • Upload date:
  • Size: 29.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.23.2 CPython/2.7.14

File hashes

Hashes for python-mbedtls-0.12.1.tar.gz
Algorithm Hash digest
SHA256 430bab0a39441e2a44c4547f5d45dd89e0bc68e67401255864ab034497c4dba7
MD5 58466da9f99d9dd83ba42ebfebf3465f
BLAKE2b-256 592eab4207c9e1d5673949b4510f0eaa835cec4cdf8ba8067896e65dd1d2a9e2

See more details on using hashes here.

File details

Details for the file python_mbedtls-0.12.1-py3.6-linux-x86_64.egg.

File metadata

  • Download URL: python_mbedtls-0.12.1-py3.6-linux-x86_64.egg
  • Upload date:
  • Size: 4.8 MB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.23.2 CPython/2.7.14

File hashes

Hashes for python_mbedtls-0.12.1-py3.6-linux-x86_64.egg
Algorithm Hash digest
SHA256 4157e3d33b227249e8b56f9bde1183eacd890fbf0d5379d5f67b552f27d4ec7c
MD5 9ce81ab951f53c3efa4db709ad4cee1a
BLAKE2b-256 4659b745e8d04b3a506d11451161788ea821e7652d5ff37bce998ecfa97862f9

See more details on using hashes here.

File details

Details for the file python_mbedtls-0.12.1-py3.5-linux-x86_64.egg.

File metadata

  • Download URL: python_mbedtls-0.12.1-py3.5-linux-x86_64.egg
  • Upload date:
  • Size: 4.7 MB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.23.2 CPython/2.7.14

File hashes

Hashes for python_mbedtls-0.12.1-py3.5-linux-x86_64.egg
Algorithm Hash digest
SHA256 7e8130d626d982d4aec79878f7f1506d611e03cb19dac95553569950fb405eec
MD5 2097245ffbca75f11b62dc4977829598
BLAKE2b-256 af36ec8616e28c9589211dbccf77948a8dbf0fba271d27df59e030ff5cd494d1

See more details on using hashes here.

File details

Details for the file python_mbedtls-0.12.1-py3.4-linux-x86_64.egg.

File metadata

  • Download URL: python_mbedtls-0.12.1-py3.4-linux-x86_64.egg
  • Upload date:
  • Size: 4.7 MB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.23.2 CPython/2.7.14

File hashes

Hashes for python_mbedtls-0.12.1-py3.4-linux-x86_64.egg
Algorithm Hash digest
SHA256 7b2ec79a019e1c9a65eab57d31e993b08d7925a5f551e24b3d36b33564edd343
MD5 80b28344391aa1369175098121dbb324
BLAKE2b-256 6dfba65998180277fc5ca1b217f9205777263bd9432a4915abe6fe3fcac53b15

See more details on using hashes here.

File details

Details for the file python_mbedtls-0.12.1-py2.7-linux-x86_64.egg.

File metadata

  • Download URL: python_mbedtls-0.12.1-py2.7-linux-x86_64.egg
  • Upload date:
  • Size: 4.3 MB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.23.2 CPython/2.7.14

File hashes

Hashes for python_mbedtls-0.12.1-py2.7-linux-x86_64.egg
Algorithm Hash digest
SHA256 d77ff6925904adfa9f44e2279f72ce74971fdde80f0657dfa6fcce3c5e3bbb5d
MD5 ddea747694fa964299528794bd7efeec
BLAKE2b-256 162ed742bec15615a0478a2e685d758ab77ddd30ef70412a8f311b5ec5329385

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