🔒Hashing, Signatures, and Encryption in Microservices
All about how hashing, digital signatures, and encryption are integrated into microservices architecture with real-world examples, calculations, and visualizations.
Last updated
const bcrypt = require('bcrypt');
const saltRounds = 10;
async function hashPassword(password) {
const hashedPassword = await bcrypt.hash(password, saltRounds);
return hashedPassword;
}
// Usage
const password = 'AirbnbUser123!';
hashPassword(password).then(hash => {
console.log('Hashed password:', hash);
// Store this hash in the database
});
// Output: Hashed password: $2b$10$X9oJYQpZviV4/MWKMoNsI.9qBmRHxp3.KWo8GZYIxMGJrK.A9.zC2const jwt = require('jsonwebtoken');
const privateKey = '-----BEGIN PRIVATE KEY-----\\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC7hoN...\\n-----END PRIVATE KEY-----';
function generateJWT(payload) {
return jwt.sign(payload, privateKey, { algorithm: 'RS256', expiresIn: '1h' });
}
// Usage
const payload = {
service: 'recommendation-engine',
action: 'get-user-preferences',
userId: '12345'
};
const token = generateJWT(payload);
console.log('JWT:', token);
// Output: JWT: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXJ2aWNlIjoicmVjb21tZW5kYXRpb24tZW5naW5lIiwiYWN0aW9uIjoiZ2V0LXVzZXItcHJlZmVyZW5jZXMiLCJ1c2VySWQiOiIxMjM0NSIsImlhdCI6MTYzMjE1MDAwMCwiZXhwIjoxNjMyMTUzNjAwfQ.Sg2kRSvQ9DqWbQ...const crypto = require('crypto');
function encryptCardData(cardNumber, publicKey) {
const buffer = Buffer.from(cardNumber, 'utf8');
const encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString('base64');
}
// Usage
const cardNumber = '4242424242424242';
const publicKey = '-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvl...\\n-----END PUBLIC KEY-----';
const encryptedCardNumber = encryptCardData(cardNumber, publicKey);
console.log('Encrypted card number:', encryptedCardNumber);
// Output: Encrypted card number: A8d4X+9gRh7zPlQH/Lk1d3lN5xGQoO8Qv4vBSJ9...