Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

11 matches
Files & data medium

Build a Secure Local Password Vault with Encrypted Storage in Python

A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.

encryption security passwords
Python
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass

class PasswordVault:
    def __init__(self, vault_file="vault.json", key_file="vault.key"):
        self.vault_file = vault_file
        self.key_file = key_file
        self.key = self._load_or_creat…
48 0 Open
Files & data medium

Encrypt and Decrypt Files Using Python

Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.

encryption decryption fernet
Python
import os
from pathlib import Path
from cryptography.fernet import Fernet

def generate_key(key_file: Path) -> bytes:
    key = Fernet.generate_key()
    key_file.write_bytes(key)
    return key

def load_key(key_file: Path) -> bytes:
    return key_file.read_bytes()

def encrypt_file(input_path: Path, key: bytes, out…
57 0 Open
Automation & scripting medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
35 0 Open
Auth & security at scale medium

AES GCM encryption and decryption in Python

Encrypt and decrypt data with AES-256-GCM using the cryptography library, including nonce generation and authenticated roundtrip verification.

aes-gcm cryptography encryption
Python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def aes_gcm_demo():
    plaintext = b"confidential message"
    key = AESGCM.generate_key(bit_length=256)
    aesgcm = AESGCM(key)
    nonce = os.urandom(12)
    
    ciphertext = aesgcm.encrypt(nonce, plaintext, None)
    decrypted = aesgcm.dec…
18 0 Open
Auth & security at scale medium

ECDH key agreement in Python with cryptography

Simulate ECDH key exchange between Alice and Bob, derive a shared secret, and generate a symmetric key with HKDF using the cryptography library.

ecdh cryptography key-agreement
Python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

def ecdh_mock():
    # Alice generates her key pair
    alice_private = ec.generate_private_key(ec.SECP256R1())
    alice_public = alice_pr…
15 0 Open
Auth & security at scale easy

How to Generate PKCE Code Challenge in Python

This Python script generates a PKCE code verifier and its corresponding S256 code challenge for secure OAuth2 authorization flows.

pkce oauth2 security
Python
import base64
import hashlib
import os
import secrets
import string

def generate_code_verifier(length=64):
    alphabet = string.ascii_letters + string.digits + "-._~"
    return "".join(secrets.choice(alphabet) for _ in range(length))

def generate_code_challenge(code_verifier, method="S256"):
    if method == "S256…
15 0 Open
Auth & security at scale easy

How to Generate and Verify HMAC Signatures in Python

Create and validate HMAC-SHA256 signatures with a shared secret key using Python's hmac and hashlib modules.

hmac security cryptography
Python
import hashlib
import hmac

SECRET_KEY = b"pepper-secret-2024"

def generate_hmac(message: str) -> str:
    return hmac.new(SECRET_KEY, message.encode("utf-8"), hashlib.sha256).hexdigest()

def verify_hmac(message: str, received_hmac: str) -> bool:
    expected = generate_hmac(message)
    return hmac.compare_digest(e…
15 0 Open
Auth & security at scale medium

How to Mock KMS Envelope Encryption in Python

Demonstrates a minimal mock of AWS KMS envelope encryption flow with AES-GCM data key wrapping and unwrapping.

kms encryption aes-gcm
Python
import base64
import json
import os
import hashlib


class MockKMS:
    """Minimal mock of AWS KMS envelope encryption flow."""

    def generate_data_key(self):
        # Simulate KMS returning a plaintext and encrypted data key
        plaintext_key = os.urandom(32)
        encrypted_key = hashlib.sha256(plaintext_k…
13 0 Open
Auth & security at scale medium

How to Sign and Verify with Ed25519 in Python

A minimal Ed25519 sign-and-verify helper that generates a key pair, signs a message, and checks the signature with the cryptography library.

ed25519 cryptography signing
Python
import hashlib
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization

def sign_verify_mock(
    message: bytes,
    private_key: ed25519.Ed25519PrivateKey,
    public_key: ed25519.Ed25519PublicKey
) -> tuple[bool, bytes]:
    signature = private_key.sign…
13 0 Open
Auth & security at scale medium

How to sign and verify JWT RS256 in Python

Generate RSA keys, create a JWT signed with RS256, verify its signature, and decode the payload using the cryptography library.

jwt rs256 rsa
Python
import json
import time
import base64
import hmac
import hashlib
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.utils import encode_ds…
13 0 Open
Auth & security at scale medium

Implement RSA OAEP Padding in Python

Implements OAEP-style padding with MGF1 using SHA-256 from the Python standard library for RSA encryption prep.

rsa oaep cryptography
Python
import os
import hashlib


def mgf1(seed, length, hash_func=hashlib.sha256):
    """MGF1 mask generation function."""
    output = b""
    counter = 0
    while len(output) < length:
        c = counter.to_bytes(4, "big")
        output += hash_func(seed + c).digest()
        counter += 1
    return output[:length]


…
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.