Python cryptography compiler: every module ready to import
This is a free online Python compiler set up for cryptography. The libraries you need for encryption, hashing, password storage and digital signatures are already installed: type import cryptography or from Crypto.Cipher import AES and press Run. No pip, no setup, no account.
It is made for students doing a cryptography or security course, developers trying an API before using it in a project, and anyone curious about how encryption works. Your code runs in your browser, so keys and passwords never leave your device.
Installed modules
| Package | Import | For |
|---|---|---|
| cryptography | cryptography | Fernet, AES, RSA, elliptic curves, X.509 and more (PyCA) |
| PyCryptodome | Crypto | AES, DES, ChaCha20, RSA and other low-level primitives |
| bcrypt | bcrypt | Password hashing |
| PyNaCl | nacl | libsodium: public-key boxes, secret boxes, signatures |
| hashlib | hashlib | SHA-2, SHA-3, BLAKE2, scrypt (OpenSSL build) |
| hmac and secrets | hmac, secrets | Message authentication and secure random values |
| ssl | ssl | OpenSSL bindings (no network connections in the browser) |
| rsa | rsa | Pure-Python RSA |
| ecdsa | ecdsa | Elliptic-curve signatures, including secp256k1 |
| pyotp | pyotp | Two-factor (TOTP and HOTP) codes |
Plus the whole Python standard library: base64, secrets, os.urandom, struct and more.
Examples to run
Each one opens in the compiler above, ready to run. Examples with random keys print something different each time; the others show their output.
Hash a message: SHA-256, SHA-3 and BLAKE2
One-way fingerprints of data with hashlib. Change one letter and the hash changes completely.
import hashlib
message = b"hello world"
print("SHA-256: ", hashlib.sha256(message).hexdigest())
print("SHA3-256:", hashlib.sha3_256(message).hexdigest())
print("BLAKE2b: ", hashlib.blake2b(message, digest_size=32).hexdigest())
# One small change, a completely different hash
print("SHA-256 of 'hello World':", hashlib.sha256(b"hello World").hexdigest())Output
SHA-256: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 SHA3-256: 644bcc7e564373040999aac89e7622f3ca71fba1d972fd94a31c3bfbf24e3938 BLAKE2b: 256c83b297114d201b30179f3f0ef0cace9783622da5974326b436178aeef610 SHA-256 of 'hello World': db4067cec62c58bf8b2f8982071e77c082da9e00924bf3631f3b024fa54e7d7e
Encrypt and decrypt text with Fernet
The easiest safe way to encrypt data in Python: AES with an authentication check, from the cryptography library.
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"Meet me at 7pm")
print("Key: ", key.decode())
print("Encrypted:", token.decode()[:60] + "...")
print("Decrypted:", f.decrypt(token).decode())AES-GCM with PyCryptodome
Authenticated encryption with a random key and nonce; tampering is detected when decrypting.
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
key = get_random_bytes(32) # AES-256
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(b"The secret recipe")
print("Ciphertext:", ciphertext.hex())
decryptor = AES.new(key, AES.MODE_GCM, nonce=cipher.nonce)
print("Decrypted: ", decryptor.decrypt_and_verify(ciphertext, tag).decode())
# Change one byte: decryption refuses it
tampered = bytes([ciphertext[0] ^ 1]) + ciphertext[1:]
try:
AES.new(key, AES.MODE_GCM, nonce=cipher.nonce).decrypt_and_verify(tampered, tag)
except ValueError as error:
print("Tampered message rejected:", error)Store passwords safely with bcrypt and scrypt
Never store passwords in plain text: hash them with a slow, salted function and check logins against the hash.
import bcrypt
import hashlib
import os
password = b"correct horse battery staple"
# bcrypt: the salt is stored inside the hash
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
print("bcrypt hash:", hashed.decode())
print("Right password:", bcrypt.checkpw(password, hashed))
print("Wrong password:", bcrypt.checkpw(b"hunter2", hashed))
# scrypt: keep the salt next to the hash
salt = os.urandom(16)
key = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
print("scrypt key:", key.hex()[:32] + "...")RSA: sign a message and verify the signature
Generate a 2048-bit key pair, sign with the private key and check with the public key.
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.exceptions import InvalidSignature
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
message = b"I owe Alice 10 coins"
pss = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH)
signature = private_key.sign(message, pss, hashes.SHA256())
print("Signature:", signature.hex()[:48] + "...")
public_key.verify(signature, message, pss, hashes.SHA256())
print("Signature is valid")
try:
public_key.verify(signature, b"I owe Alice 1000 coins", pss, hashes.SHA256())
except InvalidSignature:
print("Changed message: signature is NOT valid")
pem = public_key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
print(pem.decode().splitlines()[0])HMAC: check a message was not changed
A keyed hash, as used to sign webhooks and API requests. compare_digest avoids timing attacks.
import hashlib
import hmac
secret = b"my-webhook-secret"
body = b'{"order": 42, "paid": true}'
signature = hmac.new(secret, body, hashlib.sha256).hexdigest()
print("Signature:", signature)
# The receiver recomputes it and compares in constant time
received = signature
expected = hmac.new(secret, body, hashlib.sha256).hexdigest()
print("Valid:", hmac.compare_digest(received, expected))
forged = hmac.new(secret, b'{"order": 42, "paid": false}', hashlib.sha256).hexdigest()
print("Forged body valid:", hmac.compare_digest(forged, expected))Output
Signature: fa843fae93299f0a980c3242f063dd6fbf98001982bdf4cd162a7cb6fb78d607 Valid: True Forged body valid: False
Two-factor codes (TOTP) with pyotp
The 6-digit codes of authenticator apps: create a secret, generate the current code and verify it.
import pyotp
secret = pyotp.random_base32()
totp = pyotp.TOTP(secret)
print("Secret (put this in an authenticator app):", secret)
print("Current code:", totp.now())
print("Code is valid:", totp.verify(totp.now()))
print("Setup link:", totp.provisioning_uri(name="alex@example.com", issuer_name="MyApp"))ECDSA on secp256k1, the Bitcoin curve
Elliptic-curve keys are much shorter than RSA keys for the same security.
import ecdsa
signing_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
print("Private key:", signing_key.to_string().hex())
print("Public key: ", verifying_key.to_string().hex()[:64] + "...")
signature = signing_key.sign(b"send 1 coin to Maya")
print("Valid signature:", verifying_key.verify(signature, b"send 1 coin to Maya"))Public-key encryption with PyNaCl
Alice encrypts a message that only Bob can read, using libsodium's Box.
from nacl.public import Box, PrivateKey
alice = PrivateKey.generate()
bob = PrivateKey.generate()
# Alice encrypts with her private key and Bob's public key
encrypted = Box(alice, bob.public_key).encrypt(b"See you at the library")
print("Encrypted:", encrypted.hex()[:48] + "...")
# Bob decrypts with his private key and Alice's public key
print("Bob reads:", Box(bob, alice.public_key).decrypt(encrypted).decode())Caesar cipher, and how to break it
The classic cipher from cryptography class, plus a brute-force attack that tries all 25 shifts.
def caesar(text, shift):
result = ""
for ch in text:
if ch.isalpha():
base = ord("A") if ch.isupper() else ord("a")
result += chr((ord(ch) - base + shift) % 26 + base)
else:
result += ch
return result
secret = caesar("Attack at dawn", 3)
print("Encrypted:", secret)
print("Decrypted:", caesar(secret, -3))
# Breaking it: only 25 possible keys
for shift in range(1, 6):
print(shift, caesar(secret, -shift))Output
Encrypted: Dwwdfn dw gdzq Decrypted: Attack at dawn 1 Cvvcem cv fcyp 2 Buubdl bu ebxo 3 Attack at dawn 4 Zsszbj zs czvm 5 Yrryai yr byul
What works, and what doesn’t
- Encryption and decryption (AES, ChaCha20, Fernet, RSA), hashing, HMAC, key derivation and signatures all work.
- Random values come from your browser’s secure random generator, so
secretsandos.urandomare safe to use. - There is no network: code cannot open HTTPS connections or call web APIs.
- The libraries are built for the web from slightly older releases (for example OpenSSL 1.1.1): fine for learning and testing, not a replacement for your production setup.
Frequently asked questions
Which cryptography modules are installed?
cryptography (PyCA), PyCryptodome (import Crypto), bcrypt, PyNaCl (import nacl), hashlib with OpenSSL (scrypt, SHA-3, BLAKE2), hmac, secrets, ssl, rsa, ecdsa and pyotp. They load in the background when the page opens, so import works straight away.
Do I need to pip install anything?
No. Everything in the list above is ready to import. For other pure-Python packages, type the name in the pip install box above the editor.
Are my keys and passwords sent anywhere?
No. Your code runs in your own browser, on your own device. Nothing you type or generate is sent to a server, which makes it a safe place to experiment.
Can I connect to a website over HTTPS?
No. Python in the browser cannot open network connections, so the ssl module works for its functions and constants but not for real TLS connections. Hashing, encryption, signatures and key generation all work.
Should I use this for production secrets?
Use it to learn, test and prototype. It runs OpenSSL 1.1.1 compiled for the web; for production systems, run your code with current, maintained library versions on your own servers.
Is pycryptodomex or argon2 available?
Not as ready-made packages. Use PyCryptodome with import Crypto (the same code as Cryptodome, different name), and bcrypt or hashlib.scrypt for password hashing instead of argon2.
Need data science libraries instead? The Python playground has numpy, pandas and scipy ready. New to Python? Start with the free beginner course.