Practical Guide to Text Encryption and Decryption: Methods, Tools, and Examples

Step-by-Step: Implementing Text Encryption and Decryption in Python and JavaScript

Overview

This guide shows practical, secure ways to encrypt and decrypt text using Python and JavaScript. We’ll use AES-GCM (authenticated symmetric encryption) because it provides confidentiality and integrity. Examples include generating keys, encrypting, decrypting, and handling binary/text conversion.

Security notes (brief)

  • Use authenticated algorithms (AES-GCM).
  • Never reuse a key/IV pair; use a random IV per message.
  • Protect keys (do not hard-code in production).
  • For transport, send ciphertext, IV, and authentication tag together (or use a combined format).

Python: AES-GCM with cryptography

Install:

bash
pip install cryptography

Code (complete example):

python
from cryptography.hazmat.primitives.ciphers.aead import AESGCMimport osimport base64 def generate_key(): return AESGCM.generate_key(bit_length=256) # 32 bytes def encrypt(plaintext: str, key: bytes) -> str: aesgcm = AESGCM(key) iv = os.urandom(12) # 96-bit recommended for GCM ciphertext = aesgcm.encrypt(iv, plaintext.encode(‘utf-8’), None) # Combine iv + ciphertext and base64 for safe transport/storage return base64.b64encode(iv + ciphertext).decode(‘utf-8’) def decrypt(token_b64: str, key: bytes) -> str: data = base64.b64decode(token_b64) iv = data[:12] ciphertext = data[12:] aesgcm = AESGCM(key) plaintext = aesgcm.decrypt(iv, ciphertext, None) return plaintext.decode(‘utf-8’)

Example usageif name == “main”: key = generate_key() secret = “Hello, world!” token = encrypt(secret, key) print(“Token:”, token) recovered = decrypt(token, key) print(“Recovered:”, recovered)

Notes:

  • The output token contains IV + ciphertext+tag (AESGCM from cryptography appends tag to ciphertext).
  • Store the key securely (e.g., environment variables, OS key store, or KMS).

JavaScript (Node.js and Browser): Web Crypto / crypto module

Node.js (built-in crypto, v14+):

javascript
// Node.js AES-GCM exampleconst crypto = require(‘crypto’);
 

function generateKey() { return crypto.randomBytes(32); // 256-bit key} function encrypt(plaintext, key) { const iv = crypto.randomBytes(12); // 96-bit const cipher = crypto.createCipheriv(‘aes-256-gcm’, key, iv); const encrypted = Buffer.concat([cipher.update(plaintext, ‘utf8’), cipher.final()]); const tag = cipher.getAuthTag(); // return base64(iv + tag + ciphertext) return Buffer.concat([iv, tag, encrypted]).toString(‘base64’);} function decrypt(tokenB64, key) { const data = Buffer.from(tokenB64, ‘base64’); const iv = data.slice(0, 12); const tag = data.slice(12, 28); // 16-byte tag const ciphertext = data.slice(28); const decipher = crypto.createDecipheriv(‘aes-256-gcm’, key, iv); decipher.setAuthTag(tag); const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]); return decrypted.toString(‘utf8’);} // Exampleconst key = generateKey();const secret = “Hello, world!”;const token

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *