Learn cryptography fundamentals and how encryption protects data.
Learn cryptography fundamentals and how encryption protects data.
Master the fundamental concepts of encryption and understand how it protects data with comprehensive examples and practical implementations.
Content by: Vatsal Vadariya
Cybersecurity Specialist
Encryption is the process of converting readable data (plaintext) into an unreadable format (ciphertext) using a mathematical algorithm and a secret key. Think of it as a digital lockbox - only someone with the right key can open it and read the contents. This is the foundation of modern cybersecurity and data protection.
# Example: Comprehensive Encryption Implementation
// Node.js encryption examples using various algorithms
const crypto = require('crypto');
// 1. Symmetric Encryption (AES-256-GCM)
class SymmetricEncryption {
constructor() {
this.algorithm = 'aes-256-gcm';
this.keyLength = 32; // 256 bits
this.ivLength = 16; // 128 bits
this.tagLength = 16; // 128 bits
}
generateKey() {
return crypto.randomBytes(this.keyLength);
}
generateIV() {
return crypto.randomBytes(this.ivLength);
}
encrypt(plaintext, key) {
const iv = this.generateIV();
const cipher = crypto.createCipher(this.algorithm, key);
cipher.setAAD(Buffer.from('additional-data', 'utf8'));
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
const tag = cipher.getAuthTag();
return {
encrypted,
iv: iv.toString('hex'),
tag: tag.toString('hex')
};
}
decrypt(encryptedData, key, iv, tag) {
const decipher = crypto.createDecipher(this.algorithm, key);
decipher.setAAD(Buffer.from('additional-data', 'utf8'));
decipher.setAuthTag(Buffer.from(tag, 'hex'));
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
}
// 2. Asymmetric Encryption (RSA)
class AsymmetricEncryption {
constructor() {
this.keySize = 2048;
}
generateKeyPair() {
return crypto.generateKeyPairSync('rsa', {
modulusLength: this.keySize,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
}
encrypt(plaintext, publicKey) {
return crypto.publicEncrypt(publicKey, Buffer.from(plaintext, 'utf8')).toString('hex');
}
decrypt(ciphertext, privateKey) {
return crypto.privateDecrypt(privateKey, Buffer.from(ciphertext, 'hex')).toString('utf8');
}
}
// 3. Hashing (SHA-256)
class Hashing {
constructor() {
this.algorithm = 'sha256';
}
hash(data) {
return crypto.createHash(this.algorithm).update(data).digest('hex');
}
hashWithSalt(data, salt) {
return crypto.createHash(this.algorithm).update(data + salt).digest('hex');
}
verifyHash(data, hash) {
return this.hash(data) === hash;
}
}
// 4. Digital Signatures
class DigitalSignature {
constructor() {
this.algorithm = 'RSA-SHA256';
}
sign(data, privateKey) {
const sign = crypto.createSign(this.algorithm);
sign.update(data);
return sign.sign(privateKey, 'hex');
}
verify(data, signature, publicKey) {
const verify = crypto.createVerify(this.algorithm);
verify.update(data);
return verify.verify(publicKey, signature, 'hex');
}
}
// 5. Password Hashing (bcrypt)
const bcrypt = require('bcrypt');
class PasswordSecurity {
constructor() {
this.saltRounds = 12;
}
async hashPassword(password) {
return await bcrypt.hash(password, this.saltRounds);
}
async verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
}
// Example usage
async function demonstrateEncryption() {
console.log("=== ENCRYPTION DEMONSTRATION ===
");
// Symmetric encryption
const symEnc = new SymmetricEncryption();
const key = symEnc.generateKey();
const plaintext = "This is sensitive data that needs protection";
console.log("1. Symmetric Encryption (AES-256-GCM):");
console.log("Original:", plaintext);
const encrypted = symEnc.encrypt(plaintext, key);
console.log("Encrypted:", encrypted.encrypted);
const decrypted = symEnc.decrypt(encrypted.encrypted, key, encrypted.iv, encrypted.tag);
console.log("Decrypted:", decrypted);
console.log("Match:", plaintext === decrypted);
console.log();
// Asymmetric encryption
const asymEnc = new AsymmetricEncryption();
const { publicKey, privateKey } = asymEnc.generateKeyPair();
console.log("2. Asymmetric Encryption (RSA):");
const encryptedRSA = asymEnc.encrypt(plaintext, publicKey);
console.log("Encrypted:", encryptedRSA);
const decryptedRSA = asymEnc.decrypt(encryptedRSA, privateKey);
console.log("Decrypted:", decryptedRSA);
console.log("Match:", plaintext === decryptedRSA);
console.log();
// Hashing
const hashing = new Hashing();
const hash = hashing.hash(plaintext);
console.log("3. Hashing (SHA-256):");
console.log("Original:", plaintext);
console.log("Hash:", hash);
console.log("Verification:", hashing.verifyHash(plaintext, hash));
console.log();
// Digital signatures
const digitalSig = new DigitalSignature();
const signature = digitalSig.sign(plaintext, privateKey);
console.log("4. Digital Signature:");
console.log("Data:", plaintext);
console.log("Signature:", signature);
console.log("Verification:", digitalSig.verify(plaintext, signature, publicKey));
console.log();
// Password hashing
const passwordSec = new PasswordSecurity();
const password = "MySecurePassword123!";
const passwordHash = await passwordSec.hashPassword(password);
console.log("5. Password Hashing (bcrypt):");
console.log("Password:", password);
console.log("Hash:", passwordHash);
console.log("Verification:", await passwordSec.verifyPassword(password, passwordHash));
}
// Run demonstration
demonstrateEncryption().catch(console.error);
# Mini-Project: Encryption Security Assessment
// Assess the security of different encryption implementations
const encryptionAssessment = {
algorithms: {
aes128: {
name: "AES-128",
keySize: 128,
securityLevel: "Good",
performance: "Fast",
useCase: "General purpose encryption",
vulnerabilities: ["Brute force (theoretical)", "Side-channel attacks"],
recommendations: ["Use AES-256 for high security", "Implement proper key management"]
},
aes256: {
name: "AES-256",
keySize: 256,
securityLevel: "Excellent",
performance: "Good",
useCase: "High security applications",
vulnerabilities: ["Side-channel attacks", "Implementation flaws"],
recommendations: ["Use authenticated encryption", "Regular security audits"]
},
rsa1024: {
name: "RSA-1024",
keySize: 1024,
securityLevel: "Weak",
performance: "Fast",
useCase: "Legacy systems only",
vulnerabilities: ["Factoring attacks", "Brute force"],
recommendations: ["Upgrade to RSA-2048 or higher", "Consider ECC alternatives"]
},
rsa2048: {
name: "RSA-2048",
keySize: 2048,
securityLevel: "Good",
performance: "Medium",
useCase: "Digital signatures, key exchange",
vulnerabilities: ["Factoring attacks (theoretical)", "Implementation flaws"],
recommendations: ["Use RSA-4096 for long-term security", "Regular key rotation"]
},
ecc256: {
name: "ECC P-256",
keySize: 256,
securityLevel: "Excellent",
performance: "Fast",
useCase: "Mobile devices, IoT",
vulnerabilities: ["Implementation flaws", "Side-channel attacks"],
recommendations: ["Use P-384 for high security", "Proper implementation"]
}
}
};
// Calculate encryption security score
function calculateEncryptionScore(algorithm) {
let score = 0;
// Key size (40 points)
if (algorithm.keySize >= 256) score += 40;
else if (algorithm.keySize >= 2048) score += 35;
else if (algorithm.keySize >= 128) score += 25;
else if (algorithm.keySize >= 1024) score += 15;
else score += 5;
// Security level (30 points)
const securityScores = {
"Excellent": 30,
"Good": 20,
"Medium": 10,
"Weak": 5
};
score += securityScores[algorithm.securityLevel] || 0;
// Performance (20 points)
const performanceScores = {
"Fast": 20,
"Good": 15,
"Medium": 10,
"Slow": 5
};
score += performanceScores[algorithm.performance] || 0;
// Vulnerability count (10 points)
const vulnCount = algorithm.vulnerabilities.length;
if (vulnCount === 0) score += 10;
else if (vulnCount <= 1) score += 8;
else if (vulnCount <= 2) score += 5;
else score += 2;
return Math.min(score, 100);
}
// Assess each encryption algorithm
console.log("ENCRYPTION ALGORITHM SECURITY ASSESSMENT");
console.log("========================================");
Object.keys(encryptionAssessment.algorithms).forEach(key => {
const algorithm = encryptionAssessment.algorithms[key];
const score = calculateEncryptionScore(algorithm);
console.log(`
${algorithm.name.toUpperCase()}:`);
console.log(` Key Size: ${algorithm.keySize} bits`);
console.log(` Security Level: ${algorithm.securityLevel}`);
console.log(` Performance: ${algorithm.performance}`);
console.log(` Use Case: ${algorithm.useCase}`);
console.log(` Security Score: ${score}/100`);
console.log(` Vulnerabilities: ${algorithm.vulnerabilities.join(', ')}`);
console.log(` Recommendations: ${algorithm.recommendations.join(', ')}`);
});
// Generate encryption recommendations
function generateEncryptionRecommendations() {
return [
"Use AES-256 for symmetric encryption",
"Use RSA-2048 or ECC P-256 for asymmetric encryption",
"Implement proper key management and rotation",
"Use authenticated encryption (AES-GCM) when possible",
"Generate cryptographically secure random keys",
"Store keys separately from encrypted data",
"Use different keys for different purposes",
"Regularly audit encryption implementations",
"Consider hardware security modules (HSM) for key storage",
"Implement proper error handling and logging"
];
}
console.log("
ENCRYPTION SECURITY RECOMMENDATIONS:");
const recommendations = generateEncryptionRecommendations();
recommendations.forEach((rec, index) => {
console.log(`${index + 1}. ${rec}`);
});
// Encryption checklist
const encryptionChecklist = {
basic: [
"Strong encryption algorithm selected",
"Proper key size implemented",
"Keys generated securely",
"Encryption implemented correctly",
"Decryption working properly"
],
advanced: [
"Key management system in place",
"Regular key rotation implemented",
"Authenticated encryption used",
"Side-channel attack protection",
"Security audit completed"
]
};
console.log("
ENCRYPTION SECURITY CHECKLIST:");
console.log("Basic Security:");
encryptionChecklist.basic.forEach((item, index) => {
console.log(`${index + 1}. ${item}`);
});
console.log("
Advanced Security:");
encryptionChecklist.advanced.forEach((item, index) => {
console.log(`${index + 1}. ${item}`);
});
Test your understanding of this topic:
Learn the differences between symmetric and asymmetric encryption methods.
Content by: Vatsal Vadariya
Cybersecurity Specialist
Test your understanding of this topic:
Understand how digital signatures provide authentication and integrity verification.
Content by: Vatsal Vadariya
Cybersecurity Specialist
Test your understanding of this topic:
Learn about password hashing and secure password storage practices.
Content by: Vatsal Vadariya
Cybersecurity Specialist
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 8