Chapter
Kriptografi adalah ilmu mengamankan komunikasi dengan mengubah data menjadi format yang tidak bisa dibaca tanpa kunci rahasia.
const crypto = require('crypto')
// SHA-256 (jangan untuk password!)
const hash = crypto
.createHash('sha256')
.update('data saya')
.digest('hex')
console.log(hash)
// 3b9c9f3d... (64 karakter hex, selalu sama untuk input yang sama)
// Gunakan untuk: checksum file, token, tanda tangan data
// JANGAN gunakan untuk: password!const bcrypt = require('bcryptjs')
// Hash password
async function hashPassword(password) {
const salt = await bcrypt.genSalt(12) // cost factor
return bcrypt.hash(password, salt)
}
// Verifikasi
async function checkPassword(input, hash) {
return bcrypt.compare(input, hash)
}
// Kenapa bcrypt, bukan SHA-256?
// - bcrypt by design lambat (melawan brute force)
// - Setiap hash punya salt unik (melawan rainbow table)
// - Cost factor bisa dinaikkan seiring waktuSatu kunci untuk enkripsi dan dekripsi.
const crypto = require('crypto')
const KEY = crypto.randomBytes(32) // 256-bit key
const IV = crypto.randomBytes(16) // initialization vector
// Enkripsi
function encrypt(text) {
const cipher = crypto.createCipheriv('aes-256-cbc', KEY, IV)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return encrypted
}
// Dekripsi
function decrypt(encrypted) {
const decipher = crypto.createDecipheriv('aes-256-cbc', KEY, IV)
let decrypted = decipher.update(encrypted, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
}
const terenkripsi = encrypt("Data rahasia")
const asli = decrypt(terenkripsi)Dua kunci berbeda — public key untuk enkripsi, private key untuk dekripsi.
Public Key → siapapun bisa punya → untuk ENKRIPSI
Private Key → rahasia, hanya pemilik → untuk DEKRIPSI
Analogi:
Public key = gembok terbuka yang kamu bagikan ke semua orang
Private key = kunci gembok yang kamu simpan sendiri
Dipakai di: HTTPS, SSH, JWT (RS256), SSL Certificate| Hashing | Enkripsi | |
|---|---|---|
| Reversible | ❌ Tidak | ✅ Ya (dengan kunci) |
| Tujuan | Verifikasi integritas | Kerahasiaan data |
| Output | Fixed length | Variabel |
| Contoh | bcrypt, SHA-256 | AES, RSA |