What is Cryptography?
Cryptography is the science of securing information by transforming it into an unreadable format, only reversible by those possessing the appropriate key. It underpins secure communications, data integrity, and authentication in modern digital systems.
Symmetric Encryption
Symmetric algorithms use the same secret key for encryption and decryption. Common examples include AES, DES, and Blowfish.
// AES encryption using Web Crypto API
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
new TextEncoder().encode("Hello, world!")
);
console.log(new Uint8Array(ciphertext));
Asymmetric Encryption
Asymmetric algorithms use a key pair: a public key for encryption and a private key for decryption. RSA and Elliptic Curve Cryptography (ECC) are typical choices.
// RSA key generation (Node.js)
const { generateKeyPairSync } = require('crypto');
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
console.log(publicKey);
console.log(privateKey);
Hash Functions
Hash functions produce a fixed-size digest from arbitrary input data. They are crucial for password storage and data integrity checks. SHA-256, SHA-3, and BLAKE2 are widely used.
// SHA-256 hashing with Web Crypto API
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
sha256('MSDN Blog').then(console.log);
Digital Signatures
Digital signatures verify the authenticity and integrity of a message. They combine hashing and asymmetric encryption.
// Signing with ECDSA (Node.js)
const { generateKeyPairSync, sign, verify } = require('crypto');
const { privateKey, publicKey } = generateKeyPairSync('ec', {
namedCurve: 'secp256k1',
privateKeyEncoding: { format: 'pem', type: 'pkcs8' },
publicKeyEncoding: { format: 'pem', type: 'spki' }
});
const data = Buffer.from('Important message');
const signature = sign(null, data, privateKey);
console.log('Signature:', signature.toString('hex'));
console.log('Verified:', verify(null, data, publicKey, signature));
Best Practices
- Prefer proven libraries over custom implementations.
- Use AES‑GCM or ChaCha20‑Poly1305 for symmetric encryption.
- Employ RSA‑2048 or ECC (secp256r1) for asymmetric operations.
- Store passwords with a slow KDF like Argon2id.
- Never reuse IVs or nonces with the same key.