A Python implementation of secure message exchange using JSON Web Encryption (JWE) and JSON Web Signature (JWS).
This project implements a secure message exchange system using:
- JSON Web Encryption (JWE) for confidentiality
- JSON Web Signature (JWS) for authenticity and integrity
- Hybrid encryption (RSA + AES) for efficiency
- Digital signatures for message authentication
- Hybrid encryption combining RSA and AES
- Secure key exchange using RSA-OAEP-256
- Payload encryption using AES-256-GCM
- Message signing using RSA-SHA256
- Complete message integrity and authenticity verification
JWE provides a way to encrypt content with a two-step encryption process:
-
Key Encryption
- Generates a random Content Encryption Key (CEK)
- Encrypts CEK with recipient's public key using
RSA-OAEP-256
- This allows secure key sharing between parties
-
Content Encryption
- Encrypts actual payload using
AES-256-GCM
with the CEK - Uses randomly generated IV for each encryption
- GCM mode provides authenticated encryption
- Encrypts actual payload using
JWE Structure:
base64url(header).
base64url(encrypted_key).
base64url(iv).
base64url(ciphertext).
base64url(auth_tag)
JWS provides a way to digitally sign content:
- Takes the entire JWE as input
- Creates a signature using sender's private key
- Uses
RSA-SHA256
for signing
JWS Structure:
base64url(header).
base64url(payload).
base64url(signature)
-
Generate and Encrypt CEK
cek = generate_random_key() encrypted_cek = rsa_encrypt(cek, receiver_public_key)
-
Encrypt Payload
iv = generate_random_iv() ciphertext, auth_tag = aes_gcm_encrypt(payload, cek, iv)
-
Create JWE
- Combine all components with base64url encoding
- Format:
header.encrypted_key.iv.ciphertext.auth_tag
-
Sign JWE
- Create signing input:
jws_header.jwe_string
- Generate signature using sender's private key
- Create final JWS:
jws_header.jwe_string.signature
- Create signing input:
-
Verify Signature
- Split JWS into components
- Verify signature using sender's public key
- Extract JWE if signature is valid
-
Decrypt Content
- Split JWE into components
- Decrypt CEK using receiver's private key
- Use CEK to decrypt payload
- Verify authentication tag
from encrypt_and_sign import JWEJWSCrypto
from decrypt_and_verify import JWEJWSDecryptor
# Initialize with keys
crypto = JWEJWSCrypto(receiver_public_key, sender_private_key)
decryptor = JWEJWSDecryptor(sender_public_key, receiver_private_key)
# Encrypt and sign
encrypted_message = crypto.encrypt_and_sign("Secret message")
# Verify and decrypt
decrypted_message = decryptor.verify_and_decrypt(encrypted_message)
- Clone the repository:
git clone https://github.com/adimyth/secure-message-exchange.git
- Install requirements:
pip install cryptography
- Use strong key pairs (minimum 2048 bits for RSA)
- Securely manage private keys
- Use secure random number generation
- Each message uses fresh CEK and IV
- OAEP padding prevents padding oracle attacks