Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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…
Encrypt and Decrypt Files Using Python
Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.
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…
How to Create a Password Protected Zip Archive in Python
Generate a password-protected zip archive and verify password correctness using the standard library zipfile module.
import zipfile
import tempfile
import os
def create_password_protected_zip(zip_path, password: str, files: dict):
"""
Create a zip archive with password protection (mock encryption).
Args:
zip_path: Path where the zip file will be created
password: Password for the archive
files:…
How to Decrypt a GPG File with a Passphrase in Python
Decrypt a GPG-encrypted file using a passphrase via the gpg CLI wrapped in a reusable Python function.
import subprocess
import tempfile
from pathlib import Path
def decrypt_gpg_file(input_file: str, passphrase: str) -> str:
"""Decrypt a GPG file using a passphrase and return the plaintext."""
result = subprocess.run(
["gpg", "--batch", "--yes", "--passphrase", passphrase, "--decrypt", input_file],
…
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.
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…
ChaCha20-Poly1305 mock in Python
Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.
from hashlib import sha256
import struct
def chacha20_block(key, counter, nonce):
"""Mock ChaCha20 block: deterministic pseudo-random keystream from key+counter+nonce."""
state_input = key + struct.pack("<I", counter) + nonce + b"ChaCha20"
return sha256(state_input).digest()[:64] # 64-byte keystream bloc…
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.
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…
Implement RSA OAEP Padding in Python
Implements OAEP-style padding with MGF1 using SHA-256 from the Python standard library for RSA encryption prep.
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]
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.