Libsodium Cryptography

GRATIS CON POSSIBILITÀ DI UPGRADE
Health Check

N/A

Torna a tutti i tutorial (2)

Public Key / Private Key Encryption with Python and REquests

This tutorial describes how to use the sealed_box encryption method, which encrypts using a public key and decrypts using a private key.

It uses python3 and the requests library.

Setup

Import the requests library, set the API url, and make sure to send the correct headers.

import requests
url = "https://libsodium-cryptography.p.rapidapi.com/api/1.0"
headers = {
    "X-RapidAPI-Key": "<your-rapid-api-key>",
    "Content-Type": "application/json"
}

Create a key pair

Generate a public key and private key on the recipient’s environment. Share the public key with the message sender.

key_request = requests.post(url + "/crypto_box_keypair", headers)
keys = key_request.json().data
public_key = keys["publicKey"]
private_key = keys["privateKey"]

Signing and Verifying a Message

Create a message that will be encrypted

message = "This is a secret message"

Encrypt a message

Encrypt a message using the shared recipient’s public key.

encrypt_body = {
    "message": message,
    "publicKey": public_key
}
encrypt_request = requests.post(url + "/crypto_box_seal", json=encrypt_body, headers)
encrypted_message = sign_request.json().data

Decrypt a message

On the recipient’s environment, decrypt the message using its private key

decrypt_body = {
    "ciphertext": encrypted_message,
    "privateKey": private_key
}
verify_request = requests.post(url + "/crypto_box_open", json=decrypt_body, headers)
decrypted_message = sign_request.json().data

print("decrypted message: " + str(decrypted_message))
# expect "decrypted message: this is a secret message"