Convert Figma logo to code with AI

pyca logocryptography

cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.

6,547
1,503
6,547
46

Top Related Projects

25,386

TLS/SSL and crypto library

LibreSSL Portable itself. This includes the build scaffold and compatibility layer that builds portable LibreSSL from the OpenBSD source code. Pull requests or patches sent to tech@openbsd.org are welcome.

12,174

A modern, portable, easy to use crypto library.

13,468

Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Quick Overview

pyca/cryptography is a Python library that provides cryptographic recipes and primitives to developers. It aims to be a comprehensive and easy-to-use cryptography library for Python, offering both high-level recipes and low-level interfaces to common cryptographic algorithms.

Pros

  • Comprehensive: Covers a wide range of cryptographic operations and algorithms
  • Well-documented: Extensive documentation and examples for easy implementation
  • Actively maintained: Regular updates and security patches
  • Cross-platform: Works on various operating systems and Python versions

Cons

  • Learning curve: Can be complex for beginners due to the breadth of cryptographic concepts
  • Performance: Some operations may be slower compared to specialized libraries
  • Dependency management: Requires careful handling of dependencies and version compatibility

Code Examples

  1. Symmetric encryption using Fernet:
from cryptography.fernet import Fernet

key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"Secret message")
decrypted = f.decrypt(token)
print(decrypted)  # b'Secret message'
  1. Generating and verifying digital signatures:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa

private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)
public_key = private_key.public_key()

message = b"Sign this message"
signature = private_key.sign(
    message,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)

public_key.verify(
    signature,
    message,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)
  1. Hashing data:
from cryptography.hazmat.primitives import hashes

digest = hashes.Hash(hashes.SHA256())
digest.update(b"Hash this data")
hash_value = digest.finalize()
print(hash_value.hex())

Getting Started

To get started with pyca/cryptography, follow these steps:

  1. Install the library using pip:

    pip install cryptography
    
  2. Import the necessary modules in your Python script:

    from cryptography.fernet import Fernet
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import rsa, padding
    
  3. Start using the library's functions and classes as shown in the code examples above.

For more detailed information and advanced usage, refer to the official documentation at https://cryptography.io/en/latest/.

Competitor Comparisons

25,386

TLS/SSL and crypto library

Pros of OpenSSL

  • Comprehensive and widely-used cryptographic library with extensive functionality
  • Supports a broader range of cryptographic algorithms and protocols
  • Offers both high-level and low-level APIs for fine-grained control

Cons of OpenSSL

  • More complex API, steeper learning curve for developers
  • Written in C, which can be less accessible for Python developers
  • Requires manual memory management, potentially leading to security vulnerabilities

Code Comparison

OpenSSL (C):

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
EVP_CIPHER_CTX_free(ctx);

Cryptography (Python):

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()

The Cryptography library provides a more Pythonic and user-friendly API, making it easier for Python developers to implement cryptographic operations. However, OpenSSL offers more extensive functionality and finer control over cryptographic operations, albeit with a more complex API.

LibreSSL Portable itself. This includes the build scaffold and compatibility layer that builds portable LibreSSL from the OpenBSD source code. Pull requests or patches sent to tech@openbsd.org are welcome.

Pros of LibreSSL

  • Written in C, offering potentially better performance for low-level cryptographic operations
  • Designed as a drop-in replacement for OpenSSL, providing compatibility with existing systems
  • Focuses on security and code cleanliness, with a history of removing vulnerable or deprecated features

Cons of LibreSSL

  • Limited to C/C++ applications, lacking native Python support
  • Smaller community and fewer contributors compared to cryptography
  • May require more manual memory management and have a steeper learning curve for developers

Code Comparison

cryptography (Python):

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"Secret message")

LibreSSL (C):

#include <openssl/evp.h>
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);

The cryptography library provides a higher-level, more Pythonic API for encryption tasks, while LibreSSL offers lower-level control but requires more code for similar operations. cryptography is better suited for Python developers, while LibreSSL is ideal for C/C++ projects or systems requiring OpenSSL compatibility.

12,174

A modern, portable, easy to use crypto library.

Pros of libsodium

  • Designed for ease of use and high-level abstractions
  • Cross-platform support with consistent behavior across systems
  • Focuses on modern, secure cryptographic primitives

Cons of libsodium

  • Limited flexibility for custom implementations
  • Smaller ecosystem and fewer third-party integrations
  • Less comprehensive documentation compared to cryptography

Code Comparison

libsodium example (encryption):

unsigned char ciphertext[crypto_secretbox_MACBYTES + MESSAGE_LEN];
crypto_secretbox_easy(ciphertext, message, MESSAGE_LEN, nonce, key);

cryptography example (encryption):

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
encrypted = f.encrypt(message)

Both libraries aim to provide secure cryptographic operations, but they differ in their approach and target audience. libsodium focuses on simplicity and modern algorithms, while cryptography offers more flexibility and a wider range of cryptographic primitives.

libsodium is particularly well-suited for projects requiring cross-platform consistency and ease of use. On the other hand, cryptography provides a more comprehensive toolkit for Python developers, with extensive documentation and a larger ecosystem of tools and integrations.

The choice between the two depends on specific project requirements, target platform, and the level of cryptographic customization needed.

13,468

Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Pros of Tink

  • Designed for ease of use with high-level abstractions
  • Supports multiple programming languages (C++, Java, Go, Python)
  • Provides built-in key management and rotation features

Cons of Tink

  • Less mature and less widely adopted than Cryptography
  • Smaller community and fewer third-party integrations
  • More opinionated, which may limit flexibility for advanced use cases

Code Comparison

Tink (Python):

from tink import aead, tink_config

tink_config.register()
keyset_handle = tink.new_keyset_handle(aead.aead_key_templates.AES128_GCM)
aead_primitive = keyset_handle.primitive(aead.Aead)

ciphertext = aead_primitive.encrypt(b"plaintext", b"associated_data")

Cryptography (Python):

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

key = AESGCM.generate_key(bit_length=128)
aesgcm = AESGCM(key)
nonce = os.urandom(12)

ciphertext = aesgcm.encrypt(nonce, b"plaintext", b"associated_data")

Both libraries provide cryptographic functionality, but Tink offers a higher-level API with built-in key management, while Cryptography provides more granular control over cryptographic operations. Tink's multi-language support and key rotation features make it attractive for large-scale projects, while Cryptography's maturity and extensive community support make it a solid choice for Python-specific applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

pyca/cryptography

.. image:: https://img.shields.io/pypi/v/cryptography.svg :target: https://pypi.org/project/cryptography/ :alt: Latest Version

.. image:: https://readthedocs.org/projects/cryptography/badge/?version=latest :target: https://cryptography.io :alt: Latest Docs

.. image:: https://github.com/pyca/cryptography/workflows/CI/badge.svg?branch=main :target: https://github.com/pyca/cryptography/actions?query=workflow%3ACI+branch%3Amain

cryptography is a package which provides cryptographic recipes and primitives to Python developers. Our goal is for it to be your "cryptographic standard library". It supports Python 3.7+ and PyPy3 7.3.11+.

cryptography includes both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests, and key derivation functions. For example, to encrypt something with cryptography's high level symmetric encryption recipe:

.. code-block:: pycon

>>> from cryptography.fernet import Fernet
>>> # Put this somewhere safe!
>>> key = Fernet.generate_key()
>>> f = Fernet(key)
>>> token = f.encrypt(b"A really secret message. Not for prying eyes.")
>>> token
b'...'
>>> f.decrypt(token)
b'A really secret message. Not for prying eyes.'

You can find more information in the documentation_.

You can install cryptography with:

.. code-block:: console

$ pip install cryptography

For full details see the installation documentation_.

Discussion


If you run into bugs, you can file them in our `issue tracker`_.

We maintain a `cryptography-dev`_ mailing list for development discussion.

You can also join ``#pyca`` on ``irc.libera.chat`` to ask questions or get
involved.

Security
~~~~~~~~

Need to report a security issue? Please consult our `security reporting`_
documentation.


.. _`documentation`: https://cryptography.io/
.. _`the installation documentation`: https://cryptography.io/en/latest/installation/
.. _`issue tracker`: https://github.com/pyca/cryptography/issues
.. _`cryptography-dev`: https://mail.python.org/mailman/listinfo/cryptography-dev
.. _`security reporting`: https://cryptography.io/en/latest/security/