{ "info": { "author": "Mathias Laurin", "author_email": "Mathias.Laurin@github.com", "bugtrack_url": null, "classifiers": [ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Cython", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Security :: Cryptography" ], "description": ".. vim:tw=72\n\n=======================================================\nCryptographic library for Python with Mbed TLS back end\n=======================================================\n\n.. image::\n https://circleci.com/gh/Synss/python-mbedtls/tree/develop.svg?style=svg\n :target: https://circleci.com/gh/Synss/python-mbedtls/tree/develop\n\n.. image::\n https://travis-ci.org/Synss/python-mbedtls.svg?branch=develop\n :target: https://travis-ci.org/Synss/python-mbedtls\n\n.. image::\n https://coveralls.io/repos/github/Synss/python-mbedtls/badge.svg?branch=master\n :target: https://coveralls.io/github/Synss/python-mbedtls?branch=master\n\n\n`python-mbedtls`_ is a free cryptographic library for Python that uses\n`mbed TLS`_ for back end.\n\n mbed TLS (formerly known as PolarSSL) makes it trivially easy for\n developers to include cryptographic and SSL/TLS capabilities in their\n (embedded) products, facilitating this functionality with a minimal\n coding footprint.\n\n*python-mbedtls* API follows the recommendations from:\n\n* `PEP 272`_ -- API for Block Encryption Algorithms v1.0\n* `PEP 452`_ -- API for Cryptographic Hash Functions v2.0\n* `PEP 506`_ -- Adding a Secret Module to the Standard Library\n* `PEP 543`_ -- A Unified TLS API for Python\n\nand therefore plays well with the `cryptographic services`_ from the\nPython standard library and many other cryptography libraries as well.\n\n.. _python-mbedtls: https://synss.github.io/python-mbedtls\n.. _mbed TLS: https://tls.mbed.org\n.. _PEP 272: https://www.python.org/dev/peps/pep-0272/\n.. _PEP 452: https://www.python.org/dev/peps/pep-0452/\n.. _PEP 506: https://www.python.org/dev/peps/pep-0506/\n.. _PEP 543: https://www.python.org/dev/peps/pep-0543/\n.. _cryptographic services: https://docs.python.org/3/library/crypto.html\n.. _PyCrypto: https://www.dlitz.net/software/pycrypto/\n.. _hashlib: https://docs.python.org/3.6/library/hashlib.html\n.. _hmac: https://docs.python.org/3.6/library/hmac.html\n\n\nLicense\n=======\n\n*python-mbedtls* is licensed under the MIT License (see LICENSE.txt).\nThis enables the use of *python-mbedtls* in both open source and closed\nsource projects. The MIT License is compatible with both GPL and Apache\n2.0 license under which mbed TLS is distributed.\n\n\nAPI documentation\n=================\n\nhttps://synss.github.io/python-mbedtls/\n\n\nInstallation\n============\n\nThe bindings are tested with Python 2.7, 3.4, 3.5, 3.6, and 3.7 on Linux\nand macOS.\n\n`manylinux1`_ wheels are available for 64-bit Linux systems. Install\nwith ``pip install python-mbedtls``.\n\n.. _manylinux1: https://www.python.org/dev/peps/pep-0513/\n\n\nUsage and examples\n==================\n\nNow, let us see examples using the various parts of the library.\n\n\nCheck which version of mbed TLS is being used by python-mbedtls\n---------------------------------------------------------------\n\nThe *mbedtls.version* module shows the run-time version\ninformation to mbed TLS.\n\n>>> from mbedtls import version\n>>> _ = version.version # \"mbed TLS 2.16.1\"\n>>> _ = version.version_info # (2, 16, 1)\n\n\nMessage digest\n--------------\n\nThe *mbedtls.hash* module supports MD5, SHA-1, SHA-2 (in 224, 256, 384,\nand 512-bits), and RIPEMD-160 secure hashes and message digests.\n\nHere are the examples from *hashlib* ported to *python-mbedtls*:\n\n>>> from mbedtls import hash as hashlib\n>>> m = hashlib.md5()\n>>> m.update(b\"Nobody inspects\")\n>>> m.update(b\" the spammish repetition\")\n>>> m.digest()\nb'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'\n>>> m.digest_size\n16\n>>> m.block_size\n64\n\nMore condensed:\n\n>>> hashlib.sha224(b\"Nobody inspects the spammish repetition\").hexdigest()\n'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'\n\nUsing ``new()``:\n\n>>> h = hashlib.new('ripemd160')\n>>> h.update(b\"Nobody inspects the spammish repetition\")\n>>> h.hexdigest()\n'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc'\n\n\nHMAC algorithm\n--------------\n\nThe *mbedtls.hmac* module computes HMAC.\n\nExample:\n\n>>> from mbedtls import hmac\n>>> m = hmac.new(b\"This is my secret key\", digestmod=\"md5\")\n>>> m.update(b\"Nobody inspects\")\n>>> m.update(b\" the spammish repetition\")\n>>> m.digest()\nb'\\x9d-/rj\\\\\\x98\\x80\\xb1rG\\x87\\x0f\\xe9\\xe4\\xeb'\n\nWarning:\n\nThe message is cleared after calculation of the digest. Only call\n``mbedtls.hmac.Hmac.digest()`` or ``mbedtls.hmac.Hmac.hexdigest()``\nonce per message.\n\n\nHMAC-based key derivation function (HKDF)\n-----------------------------------------\n\nThe *mbedtls.hkdf* module exposes extract-and-expand key derivation\nfunctions. The main function is ``hkdf()`` but ``extract()`` and\n``expand()`` may be used as well.\n\nExample:\n\n>>> from mbedtls import hkdf\n>>> hkdf.hkdf(\n... b\"my secret key\",\n... length=42,\n... info=b\"my cool app\",\n... salt=b\"and pepper\",\n... digestmod=hmac.sha256\n... )\nb'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'\n\nwhere *info*, *salt*, and *digestmod* are optional, although providing\n(at least) *info* is largely recommended.\n\n\nSymmetric cipher\n----------------\n\nThe *mbedtls.cipher* module provides symmetric encryption. The API\nfollows the recommendations from PEP 272 so that it can be used as a\ndrop-in replacement to other libraries.\n\n*python-mbedtls* provides the following algorithms:\n\n- AES encryption/decryption (128, 192, and 256 bits) in ECB, CBC, CFB128,\n CTR, OFB, or XTS mode;\n- AES AEAD (128, 192, and 256 bits) in GCM, or CCM mode;\n- ARC4 encryption/decryption;\n- ARIA encryption/decryption (128, 192, and 256 bits) in ECB, CBC,\n CTR, or GCM modes;\n- Blowfish encryption/decryption in ECB, CBC, CFB64, or CTR mode;\n- Camellia encryption/decryption (128, 192, and 256 bits) in ECB, CBC,\n CFB128, CTR, or GCM mode;\n- DES, DES3, and double DES3 encryption/decryption in ECB, or CBC mode;\n- CHACHA20 and CHACHA0/POLY1305 encryption/decryption.\n\nExample:\n\n>>> from mbedtls import cipher\n>>> c = cipher.AES.new(b\"My 16-bytes key.\", cipher.MODE_CBC, b\"CBC needs an IV.\")\n>>> enc = c.encrypt(b\"This is a super-secret message!\")\n>>> enc\nb'*`k6\\x98\\x97=[\\xdf\\x7f\\x88\\x96\\xf5\\t\\x19J7\\x93\\xb5\\xe0~\\t\\x9e\\x968m\\xcd\\x9c3\\x04o\\xe6'\n>>> c.decrypt(enc)\nb'This is a super-secret message!'\n\n\nRSA public key\n--------------\n\nThe *mbedtls.pk* module provides the RSA cryptosystem. This includes:\n\n- Public-private key generation and key import/export in PEM and DER\n formats;\n- asymmetric encryption and decryption;\n- message signature and verification.\n\nKey generation, the default size is 2048 bits:\n\n>>> from mbedtls import pk\n>>> rsa = pk.RSA()\n>>> prv = rsa.generate()\n>>> rsa.key_size\n256\n\nMessage encryption and decryption:\n\n>>> enc = rsa.encrypt(b\"secret message\")\n>>> rsa.decrypt(enc)\nb'secret message'\n\nMessage signature and verification:\n\n>>> sig = rsa.sign(b\"Please sign here.\")\n>>> rsa.verify(b\"Please sign here.\", sig)\nTrue\n>>> rsa.verify(b\"Sorry, wrong message.\", sig)\nFalse\n>>> pub = rsa.export_public_key(format=\"DER\")\n>>> other = pk.RSA.from_buffer(pub)\n>>> other.verify(b\"Please sign here.\", sig)\nTrue\n\n\nStatic and ephemeral Elliptic curve Diffie-Hellman\n--------------------------------------------------\n\nThe *mbedtls.pk* module provides the ECC cryptosystem. This includes:\n\n- Public-private key generation and key import/export in the PEM and DER\n formats;\n- asymmetric encrypt and decryption;\n- message signature and verification;\n- ephemeral ECDH key exchange.\n\n``get_supported_curves()`` returns the list of supported curves.\n\nThe API of the ECC class is the same as the API of the RSA class\nbut ciphering (``encrypt()`` and ``decrypt()`` is not supported by\nMbed TLS).\n\nMessage signature and verification---elliptic curve digital signature\nalgorithm (ECDSA):\n\n>>> from mbedtls import pk\n>>> ecdsa = pk.ECC()\n>>> prv = ecdsa.generate()\n>>> sig = ecdsa.sign(b\"Please sign here.\")\n>>> ecdsa.verify(b\"Please sign here.\", sig)\nTrue\n>>> ecdsa.verify(b\"Sorry, wrong message.\", sig)\nFalse\n>>> pub = ecdsa.export_public_key(format=\"DER\")\n>>> other = pk.ECC.from_buffer(pub)\n>>> other.verify(b\"Please sign here.\", sig)\nTrue\n\nThe classes ``ECDHServer`` and ``ECDHClient`` may be used for ephemeral\nECDH. The key exchange is as follows:\n\n>>> ecdh_srv = pk.ECDHServer()\n>>> ecdh_cli = pk.ECDHClient()\n\nThe server generates the ServerKeyExchange encrypted payload and\npasses it to the client:\n\n>>> ske = ecdh_srv.generate()\n>>> ecdh_cli.import_SKE(ske)\n\nthen the client generates the ClientKeyExchange encrypted payload and\npasses it back to the server:\n\n>>> cke = ecdh_cli.generate()\n>>> ecdh_srv.import_CKE(cke)\n\nNow, client and server may generate their shared secret:\n\n>>> secret = ecdh_srv.generate_secret()\n>>> ecdh_cli.generate_secret() == secret\nTrue\n>>> ecdh_srv.shared_secret == ecdh_cli.shared_secret\nTrue\n\n\nDiffie-Hellman-Merkle key exchange\n----------------------------------\n\nThe classes ``DHServer`` and ``DHClient`` may be used for DH Key\nexchange. The classes have the same API as ``ECDHServer``\nand ``ECDHClient``, respectively.\n\nThe key exchange is as follow:\n\n>>> from mbedtls.mpi import MPI\n>>> from mbedtls import pk\n>>> dh_srv = pk.DHServer(MPI.prime(128), MPI.prime(96))\n>>> dh_cli = pk.DHClient(MPI.prime(128), MPI.prime(96))\n\nThe 128-bytes prime and the 96-bytes prime are the modulus ``P``\nand the generator ``G``.\n\nThe server generates the ServerKeyExchange payload:\n\n>>> ske = dh_srv.generate()\n>>> dh_cli.import_SKE(ske)\n\nThe payload ends with ``G^X mod P`` where ``X`` is the secret value of\nthe server.\n\n>>> cke = dh_cli.generate()\n>>> dh_srv.import_CKE(cke)\n\n``cke`` is ``G^Y mod P`` (with ``Y`` the secret value from the client)\nreturned as its representation in bytes so that it can be readily\ntransported over the network.\n\nAs in ECDH, client and server may now generate their shared secret:\n\n>>> secret = dh_srv.generate_secret()\n>>> dh_cli.generate_secret() == secret\nTrue\n>>> dh_srv.shared_secret == dh_cli.shared_secret\nTrue\n\n\nX.509 Certificate writing and parsing\n-------------------------------------\n\nThe *mbedtls.x509* module can be used to parse X.509 certificates\nor create and verify a certificate chain.\n\nHere, the trusted root is a self-signed CA certificate\n``ca0_crt`` signed by ``ca0_key``.\n\n>>> import datetime as dt\n>>>\n>>> from mbedtls import hash as hashlib\n>>> from mbedtls import pk\n>>> from mbedtls import x509\n>>>\n>>> now = dt.datetime.utcnow()\n>>> ca0_key = pk.RSA()\n>>> _ = ca0_key.generate()\n>>> ca0_csr = x509.CSR.new(ca0_key, \"CN=Trusted CA\", hashlib.sha256())\n>>> ca0_crt = x509.CRT.selfsign(\n... ca0_csr, ca0_key,\n... not_before=now, not_after=now + dt.timedelta(days=90),\n... serial_number=0x123456,\n... basic_constraints=x509.BasicConstraints(True, 1))\n...\n\nAn intermediate then issues a Certificate Singing Request (CSR) that the\nroot CA signs:\n\n>>> ca1_key = pk.ECC()\n>>> _ = ca1_key.generate()\n>>> ca1_csr = x509.CSR.new(ca1_key, \"CN=Intermediate CA\", hashlib.sha256())\n>>>\n>>> ca1_crt = ca0_crt.sign(\n... ca1_csr, ca0_key, now, now + dt.timedelta(days=90), 0x123456, \n... basic_constraints=x509.BasicConstraints(ca=True, max_path_length=3))\n...\n\nAnd finally, the intermediate CA signs a certificate for the\nEnd Entity on the basis of a new CSR:\n\n>>> ee0_key = pk.ECC()\n>>> _ = ee0_key.generate()\n>>> ee0_csr = x509.CSR.new(ee0_key, \"CN=End Entity\", hashlib.sha256())\n>>>\n>>> ee0_crt = ca1_crt.sign(\n... ee0_csr, ca1_key, now, now + dt.timedelta(days=90), 0x987654)\n...\n\nThe emitting certificate can be used to verify the next certificate in\nthe chain:\n\n>>> ca1_crt.verify(ee0_crt)\nTrue\n>>> ca0_crt.verify(ca1_crt)\nTrue\n\nNote, however, that this verification is only one step in a private key\ninfrastructure and does not take CRLs, path length, etc. into account.\n\n\nTLS client and server\n---------------------\n\nThe *mbedtls.tls* module provides TLS clients and servers. The API\nfollows the recommendations of `PEP 543`_. Note, however, that the\nPython standard SSL library does not follow the PEP so that this\nlibrary may not be a drop-in replacement.\n\n.. _PEP 543: https://www.python.org/dev/peps/pep-0543/\n\nHere are some simple HTTP messages to pass from the client to the\nserver and back.\n\n>>> get_request = \"\\r\\n\".join((\n... \"GET / HTTP/1.0\",\n... \"\",\n... \"\")).encode(\"ascii\")\n...\n>>> http_response = \"\\r\\n\".join((\n... \"HTTP/1.0 200 OK\",\n... \"Content-Type: text/html\",\n... \"\",\n... \"
Successful connection.
\",\n... \"\")).encode(\"ascii\")\n...\n>>> http_error = \"\\r\\n\".join((\n... \"HTTP/1.0 400 Bad Request\",\n... \"\",\n... \"\"))\n...\n\nFor this example, the trust store just consists in the root certificate\n``ca0_crt`` from the previous section.\n\n>>> from mbedtls import tls\n>>> trust_store = tls.TrustStore()\n>>> trust_store.add(ca0_crt)\n\nThe next step is to configure the TLS contexts for server and client.\n\n>>> tls_srv_ctx = tls.ServerContext(tls.TLSConfiguration(\n... trust_store=trust_store,\n... certificate_chain=([ee0_crt, ca1_crt], ee0_key),\n... validate_certificates=False,\n... ))\n...\n>>> tls_cli_ctx = tls.ClientContext(tls.TLSConfiguration(\n... trust_store=trust_store,\n... validate_certificates=True,\n... ))\n...\n\nThe contexts are used to wrap TCP sockets.\n\n>>> import socket\n>>> tls_srv = tls_srv_ctx.wrap_socket(\n... socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n... )\n...\n\n>>> from contextlib import suppress\n>>> def block(callback, *args, **kwargs):\n... while True:\n... with suppress(tls.WantReadError, tls.WantWriteError):\n... return callback(*args, **kwargs)\n...\n\nThe server starts in its own process in this example\nbecause ``accept()`` is blocking.\n\n>>> def server_main_loop(sock):\n... conn, addr = sock.accept()\n... block(conn.do_handshake)\n... data = conn.recv(1024)\n... if data == get_request:\n... conn.sendall(http_response)\n... else:\n... conn.sendall(http_error)\n...\n\n>>> port = 4433\n>>> tls_srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n>>> tls_srv.bind((\"0.0.0.0\", port))\n>>> tls_srv.listen(1)\n\n>>> import multiprocessing as mp\n>>> runner = mp.Process(target=server_main_loop, args=(tls_srv, ))\n>>> runner.start()\n\nFinally, a client queries the server with the ``get_request``:\n\n>>> tls_cli = tls_cli_ctx.wrap_socket(\n... socket.socket(socket.AF_INET, socket.SOCK_STREAM),\n... server_hostname=None,\n... )\n...\n>>> tls_cli.connect((\"localhost\", port))\n>>> block(tls_cli.do_handshake)\n>>> tls_cli.send(get_request)\n18\n>>> response = block(tls_cli.recv, 1024)\n>>> print(response.decode(\"ascii\").replace(\"\\r\\n\", \"\\n\"))\nHTTP/1.0 200 OK\nContent-Type: text/html\nSuccessful connection.
\n