Implementing Salt with Encryption in TypeScript
If two users have the same password and you hash without a salt, they produce identical hashes. An attacker who cracks one cracks both. That's why salts e...
8 May 2024

If two users have the same password and you hash without a salt, they produce identical hashes. An attacker who cracks one cracks both. That's why salts exist.
A salt is a random string added to the input before hashing. Even identical passwords produce different hashes because each one uses a different salt.
How it works in TypeScript
import crypto from 'crypto';
const generateSalt = (length: number = 16): string => {
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
};
const encryptWithSalt = (data: string, salt: string): string => {
const hashedSalt = crypto.createHash('sha256').update(salt).digest('hex');
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(hashedSalt.slice(0, 32)), Buffer.alloc(16, 0));
let encryptedData = cipher.update(data, 'utf8', 'hex');
encryptedData += cipher.final('hex');
return encryptedData;
};
Using it:
const plaintextData = 'Sensitive information';
const salt = generateSalt();
const encryptedData = encryptWithSalt(plaintextData, salt);
console.log('Encrypted Data:', encryptedData);
console.log('Salt:', salt);
Store the salt alongside the hash
This is the part that confuses people. The salt isn't secret. Store it right next to the hashed password in your database. The salt's job isn't to be hidden — it's to make each hash unique so rainbow table attacks are useless.
The trade-off
Salted hashing protects against precomputed attacks (rainbow tables) and ensures identical inputs don't produce identical outputs. That's a big win.
But salting alone isn't enough. For password storage specifically, use a purpose-built algorithm like bcrypt, scrypt, or argon2. These algorithms are intentionally slow, which makes brute-force attacks expensive. A fast hash like SHA-256 with a salt is better than nothing, but it's not what you should reach for when storing user passwords.
Use crypto and manual salting for encryption and data integrity checks. Use bcrypt or argon2 for password hashing.