Giter Club home page Giter Club logo

hybrid-pke's Introduction

Hybrid PKE

The Hybrid Public Key Encryption (HPKE) standard in Python.

hybrid_pke = hpke-rsPyO3

This library provides Python bindings to the hpke-rs crate, which supports primitives from either Rust Crypto or EverCrypt.

Table of Contents
  1. Usage
  2. Features
  3. Installation
  4. Development
  5. Related Projects

Usage

Basic

The single-shot API is intended for single message encryption/decryption. The default HPKE configuration uses the unauthenticated Base mode, an X25519 DH key encapsulation mechanism, a SHA256 key derivation mechanism, and a ChaCha20Poly1305 AEAD function.

import hybrid_pke

hpke = hybrid_pke.default()
info = b""  # shared metadata, correspondance-level
aad = b""  # shared metadata, message-level
secret_key_r, public_key_r = hpke.generate_key_pair()  # receiver keys, pre-generated

# ============== Sender ==============

message = b"hello from the other side!"
encap, ciphertext = hpke.seal(public_key_r, info, aad, message)

# ============= Receiver =============

plaintext = hpke.open(encap, secret_key_r, info, aad, ciphertext)
print(plaintext.decode("utf-8"))
# >> hello from the other side!

Advanced

Sender & Receiver Contexts

The Sender Context and Receiver Context APIs allow for setting up a context for repeated encryptions and decryptions. It's recommended whenever you intend to perform several encryptions or decryptions in quick succession.

info = b"quotes from your favorite aphorists"
aads = [
  b"Szasz",
  b"Nietzsche",
  b"Morandotti",
  b"Brudzinski",
  b"Hubbard",
]

# ============== Sender ==============

messages = [
    b"Two wrongs don't make a right, but they make a good excuse.",
    b"Become who you are!",
    b"Only those who aren't hungry are able to judge the quality of a meal.",
    b"Under certain circumstances a wanted poster is a letter of recommendation.",
    b"Nobody ever forgets where he buried the hatchet.",
]
encap, sender_context = hpke.setup_sender(public_key_r, info)

ciphertexts = []
for aad, msg in zip(aads, messages):
    ciphertext = sender_context.seal(aad, msg)
    ciphertexts.append(ciphertext)

# ============= Receiver =============

receiver_context = hpke.setup_receiver(encap, secret_key_r, info)
plaintexts = []
for aad, ctxt in zip(aads, ciphertexts):
    plaintext = receiver_context.open(aad, ctxt)
    plaintexts.append(plaintext)

print(f"\"{plaintexts[0].decode()}\" - {aad[0].decode()}")
print(f"\"{plaintexts[1].decode()}\" - {aad[1].decode()}")
# >> "Two wrongs don't make a right, but they make a good excuse." - Szasz
# >> "Become who you are!" - Nietzsche
Mode.AUTH: Authenticated Sender

Auth mode allows for signing and verifying encryptions with a previously authenticated sender key-pair.

hpke = hybrid_pke.default(mode=hybrid_pke.Mode.AUTH)
secret_key_r, public_key_r = hpke.generate_key_pair()  # receiver keys
secret_key_s, public_key_s = hpke.generate_key_pair()  # sender keys, pre-authenticated

# ============== Sender ==============

# sign with sender's secret key
encap, ciphertext = hpke.seal(public_key_r, info, aad, message, sk_s=secret_key_s)

# ============= Receiver =============

# verify with sender's public key
plaintext = hpke.open(encap, secret_key_r, info, aad, ciphertext, pk_s=public_key_s)
Mode.PSK: Pre-shared Key Authentication

PSK mode allows for signing and verifying encryptions with a previously shared key held by both the sender and recipient.

hpke = hybrid_pke.default(mode=hybrid_pke.Mode.PSK)
# pre-shared key + ID
psk = bytes.fromhex("0247fd33b913760fa1fa51e1892d9f307fbe65eb171e8132c2af18555a738b82")
psk_id = bytes.fromhex("456e6e796e20447572696e206172616e204d6f726961")

# ============== Sender ==============

# sign with pre-shared key
encap, ciphertext = hpke.seal(public_key_r, info, aad, message, psk=psk, psk_id=psk_id)

# ============= Receiver =============

# verify with pre-shared key
plaintext = hpke.open(encap, secret_key_r, info, aad, ciphertext, psk=psk, psk_id=psk_id)
Mode.AUTH_PSK: Combining AUTH and PSK.

PSK mode allows for signing and verifying encryptions with a previously shared key held by both the sender and recipient.

hpke = hybrid_pke.default(mode=hybrid_pke.Mode.PSK)
secret_key_r, public_key_r = hpke.generate_key_pair()  # receiver keys
secret_key_s, public_key_s = hpke.generate_key_pair()  # sender keys, pre-authenticated
# pre-shared key + ID
psk = bytes.fromhex("0247fd33b913760fa1fa51e1892d9f307fbe65eb171e8132c2af18555a738b82")
psk_id = bytes.fromhex("456e6e796e20447572696e206172616e204d6f726961")

# ============== Sender ==============

# sign with both pre-shared key and sender's secret key
encap, ciphertext = hpke.seal(
    public_key_r, info, aad, message,
    psk=psk, psk_id=psk_id, sk_s=secret_key_s,
)

# ============= Receiver =============

# verify with both pre-shared key and sender's public key
plaintext = hpke.open(
    encap, secret_key_r, info, aad, ciphertext,
    psk=psk, psk_id=psk_id, pk_s=public_key_s,
)

(back to top)

Features

The features available match those supported by hpke-rs.

HPKE Modes
  • mode_base
  • mode_psk
  • mode_auth
  • mode_auth_psk
KEMs: (Diffie-Hellman) Key Encapsulation Mechanisms
  • DHKEM(P-256, HKDF-SHA256)
  • DHKEM(P-384, HKDF-SHA384)
  • DHKEM(P-521, HKDF-SHA512)
  • DHKEM(X25519, HKDF-SHA256)
  • DHKEM(X448, HKDF-SHA512)
KDFs: Key Derivation Functions
  • HKDF-SHA256
  • HKDF-SHA384
  • HKDF-SHA512
AEADs: Authenticated Encryption with Additional Data functions
  • AES-128-GCM
  • AES-256-GCM
  • ChaCha20Poly1305
  • Export only

(back to top)

Installation

Wheels for various platforms and architectures can be found on PyPI or in the wheelhouse.zip archive from the latest Github release.

The library can also be installed from source with maturin -- see below.

(back to top)

Development

We use maturin to build and distribute the PyO3 extension module as a Python wheel.

For users of cmake, we provide a Makefile that includes some helpful development commands.

Some useful tips
  • maturin develop builds & installs the Python package into your Python environment (venv or conda recommended)
  • pytest . tests the resulting Python package.
  • pytest -n auto . runs the full test suite in parallel.
  • maturin build --release -o dist --sdist builds the extension module in release-mode and produces a wheel for your environment's OS and architecture.
  • The -i/--interpreter flag for maturin can be used to swap out different Python interpreters, if you have multiple Python installations.

(back to top)

Releasing

We use cargo-release to manage release commits and git tags. Our versioning follows SemVer, and after every release we immediately bump to a prerelease version with the -dev0 suffix.

Example release flow
$ git checkout main
$ cargo release patch --execute
Upgrading hybrid_pke from X.X.X-dev0 to X.X.X
   Replacing in pyproject.toml
--- pyproject.toml      original
+++ pyproject.toml      replaced
@@ -8 +8 @@
-version = "X.X.X-dev0"  # NOTE: auto-updated during release
+version = "X.X.X"  # NOTE: auto-updated during release
$ cargo release X.X.Y-dev0 --no-tag
Upgrading hybrid_pke from X.X.X to X.X.Y-dev0
   Replacing in pyproject.toml
--- pyproject.toml      original
+++ pyproject.toml      replaced
@@ -8 +8 @@
-version = "X.X.X"  # NOTE: auto-updated during release
+version = "X.X.Y-dev0"  # NOTE: auto-updated during release
$ git push origin main
$ git push origin vX.X.X  # triggers automatic release steps in CI

(back to top)

Related Projects

(back to top)

hybrid-pke's People

Contributors

jvmncs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

hybrid-pke's Issues

investigate building hpke-rs without std

in version 0.2.0, a bunch of work was done on hpke-rs to make it no-std compatible. taking advantage of this work could reduce the size of the cdylib hybrid-pke relies on

Wheel installation failing on 64-bit Windows

On windows we are seeing the PyPI wheel failing to install, forcing pip to fall back to building from source:

Collecting hybrid-pke
  Downloading hybrid_pke-1.0.0.tar.gz (1.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.7/1.7 MB 10.1 MB/s eta 0:00:00
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]

      Cargo, the Rust package manager, is not installed or is not on PATH.
      This package requires Rust and Cargo to compile extensions. Install it through
      the system's package manager or via https://rustup.rs/

      Checking for Rust toolchain....
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Windows arch:

>>> import platform
>>> platform.architecture()
('64bit', 'WindowsPE')
>>> platform.platform()
'Windows-10-10.0.22621-SP0'

Decapsulate a encapped key from a ciphertext

Hi,

I have cypher texts with an encapsulated symmetric key (send by third party). Is it possible to decapsulate these keys using the private key? I think rust-hpke can.

I asked the question on chat gpt which came up with the code below, but the HypridPKE class it is talking about, does not exist in 1.0.1 of hybrid-pke.

from hybrid_pke import HybridPKE, HybridError

# Initialize the HybridPKE object
hybrid_pke = HybridPKE()

# Generate a key pair
private_key, public_key = hybrid_pke.generate_key_pair()

# Encrypt a message
message = b"Hello, world!"
ciphertext, encapped_key = hybrid_pke.encrypt(public_key, message)

# Decapsulate the encapped key
decapsulated_key = hybrid_pke.decapsulate(private_key, encapped_key)

# Decrypt the ciphertext using the decapsulated key
try:
    decrypted_message = hybrid_pke.decrypt(private_key, ciphertext, decapsulated_key)
    print(decrypted_message)
except HybridError as e:
    print(e)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.