Last active
December 6, 2024 20:38
-
-
Save oconnor663/4427d94dd250691013099ba8e8695fc2 to your computer and use it in GitHub Desktop.
PyNaCl demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from nacl.secret import SecretBox | |
# -------- encryption with a random nonce -------- | |
key = b"A" * 32 | |
ciphertext = SecretBox(key).encrypt(b"hello") | |
print("\nciphertext:", ciphertext) | |
plaintext = SecretBox(key).decrypt(ciphertext) | |
print("\nplaintext:", plaintext) | |
assert plaintext == b"hello" | |
# -------- encryption with a chosen nonce -------- | |
nonce = b"a" * 24 | |
ciphertext = SecretBox(key).encrypt(b"hello", nonce) | |
print("\nciphertext:", ciphertext) | |
plaintext = SecretBox(key).decrypt(ciphertext) | |
print("\nplaintext:", plaintext) | |
assert plaintext == b"hello" | |
null_ciphertext = SecretBox(key).encrypt(b"\0" * 5, nonce=nonce) | |
print("\nnull ciphertext:", null_ciphertext) | |
xor = bytearray() | |
for i in range(len(ciphertext)): | |
xor.append(ciphertext[i] ^ null_ciphertext[i]) | |
print("\nxor:", xor) | |
# -------- public key encryption -------- | |
from nacl.public import PrivateKey, Box | |
alice_private = PrivateKey.generate() | |
print("\nAlice private:", alice_private) | |
alice_public = alice_private.public_key | |
print("\nAlice public:", alice_public) | |
bob_private = PrivateKey.generate() | |
print("\nBob private:", bob_private) | |
bob_public = bob_private.public_key | |
print("\nBob public:", bob_public) | |
ciphertext = Box(alice_private, bob_public).encrypt(b"goodbye") | |
print("\nciphertext:", ciphertext) | |
plaintext = Box(bob_private, alice_public).decrypt(ciphertext) | |
print("\nplaintext:", plaintext) | |
# -------- public key signing -------- | |
from nacl.signing import SigningKey | |
signing_key = SigningKey.generate() | |
print("\nsigning key:", signing_key) | |
verify_key = signing_key.verify_key | |
print("\nverify key:", verify_key) | |
signed = signing_key.sign(b"banana") | |
print("\nsigned:", signed) | |
verify_key.verify(signed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment