Cryptography

Contents

Cryptography Fundamentals

Core Concepts

  • Confidentiality - Keeping data private
  • Integrity - Ensuring data hasn't been modified
  • Authentication - Verifying identity
  • Non-repudiation - Cannot deny actions

Types of Cryptography

  • Symmetric (Secret Key)
  • Asymmetric (Public Key)
  • Hash Functions
  • Digital Signatures

Symmetric Encryption

Common Algorithms

  • AES (128-bit, 192-bit, 256-bit)
  • ChaCha20
  • 3DES (Legacy)

AES Implementation

// Node.js - AES-GCM Implementation const crypto = require('crypto'); class AESCipher { constructor(key) { this.algorithm = 'aes-256-gcm'; // Ensure key is 32 bytes (256 bits) this.key = crypto.scryptSync(key, 'salt', 32); } encrypt(plaintext) { // Generate random IV for each encryption const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv(this.algorithm, this.key, iv); let encrypted = cipher.update(plaintext, 'utf8', 'hex'); encrypted += cipher.final('hex'); // Get authentication tag const authTag = cipher.getAuthTag(); return { iv: iv.toString('hex'), ciphertext: encrypted, authTag: authTag.toString('hex') }; } decrypt(encryptedData) { const decipher = crypto.createDecipheriv( this.algorithm, this.key, Buffer.from(encryptedData.iv, 'hex') ); decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'hex')); let decrypted = decipher.update(encryptedData.ciphertext, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } }

Asymmetric Encryption

Common Algorithms

  • RSA
  • ECC (Elliptic Curve Cryptography)
  • DSA (Digital Signature Algorithm)

RSA Implementation

// Node.js - RSA Key Generation and Usage const crypto = require('crypto'); class RSACrypto { static generateKeyPair() { return crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); } static encrypt(publicKey, data) { const encryptedData = crypto.publicEncrypt( { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, Buffer.from(data) ); return encryptedData.toString('base64'); } static decrypt(privateKey, encryptedData) { const decryptedData = crypto.privateDecrypt( { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, Buffer.from(encryptedData, 'base64') ); return decryptedData.toString(); } }

Hash Functions

Common Hash Functions

  • SHA-256
  • SHA-3
  • BLAKE2
  • Argon2 (Password Hashing)

Password Hashing Implementation

// Node.js - Secure Password Hashing const crypto = require('crypto'); class PasswordHash { static async hash(password) { return new Promise((resolve, reject) => { // Generate random salt const salt = crypto.randomBytes(16); crypto.scrypt(password, salt, 64, (err, derivedKey) => { if (err) reject(err); resolve(salt.toString('hex') + ':' + derivedKey.toString('hex')); }); }); } static async verify(password, hash) { return new Promise((resolve, reject) => { const [salt, key] = hash.split(':'); const keyBuffer = Buffer.from(key, 'hex'); crypto.scrypt(password, Buffer.from(salt, 'hex'), 64, (err, derivedKey) => { if (err) reject(err); resolve(crypto.timingSafeEqual(keyBuffer, derivedKey)); }); }); } }

Digital Signatures

Digital Signature Process

// Node.js - Digital Signature Implementation const crypto = require('crypto'); class DigitalSignature { static sign(privateKey, data) { const sign = crypto.createSign('SHA256'); sign.update(data); return sign.sign(privateKey, 'base64'); } static verify(publicKey, signature, data) { const verify = crypto.createVerify('SHA256'); verify.update(data); return verify.verify(publicKey, signature, 'base64'); } }

Certificate Generation

# OpenSSL Commands for Certificate Generation # Generate private key openssl genpkey -algorithm RSA -out private.key -pkeyopt rsa_keygen_bits:2048 # Generate CSR openssl req -new -key private.key -out cert.csr # Self-sign certificate openssl x509 -req -days 365 -in cert.csr \ -signkey private.key -out certificate.crt

Key Management

Best Practices

  • Secure key generation
  • Safe key storage
  • Regular key rotation
  • Access control
  • Backup procedures

Key Rotation Implementation

class KeyRotation { static async rotateKeys(keyStore) { // Generate new key pair const newKeyPair = await generateNewKeyPair(); // Store new keys with version const keyVersion = Date.now(); await keyStore.store({ version: keyVersion, publicKey: newKeyPair.publicKey, privateKey: newKeyPair.privateKey }); // Mark old keys as deprecated await keyStore.deprecateOldKeys(); // Schedule deletion of old keys setTimeout(async () => { await keyStore.deleteDeprecatedKeys(); }, 30 * 24 * 60 * 60 * 1000); // 30 days return keyVersion; } }

Common Implementations

TLS Configuration

// Node.js - HTTPS Server with TLS const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('private.key'), cert: fs.readFileSync('certificate.crt'), ciphers: [ 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'ECDHE-RSA-AES256-GCM-SHA384' ].join(':'), minVersion: 'TLSv1.3' }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('Secure Server!'); }).listen(443);