Security and Encryption Libraries
Security and Encryption Libraries
Privacy requires security. Modern encryption libraries provide the cryptographic primitives needed for protecting personal data. libsodium offers a high-level, easy-to-use interface for encryption, decryption, signatures, and password hashing. For JavaScript applications, the Web Crypto API provides native browser encryption capabilities.
// Using libsodium for privacy-focused encryption
const sodium = require('libsodium-wrappers');
class PrivacyEncryption {
async init() {
await sodium.ready;
}
generateKeyPair() {
// Generate key pair for user
return sodium.crypto_box_keypair();
}
encryptForUser(message, recipientPublicKey, senderSecretKey) {
// Encrypt message for specific user
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
const encrypted = sodium.crypto_box_easy(
message,
nonce,
recipientPublicKey,
senderSecretKey
);
return {
encrypted: sodium.to_base64(encrypted),
nonce: sodium.to_base64(nonce)
};
}
encryptSensitiveData(data, key) {
// Encrypt sensitive data with authenticated encryption
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const message = JSON.stringify(data);
const encrypted = sodium.crypto_secretbox_easy(
message,
nonce,
key
);
return {
encrypted: sodium.to_base64(encrypted),
nonce: sodium.to_base64(nonce)
};
}
hashPassword(password) {
// Hash password with salt
return sodium.crypto_pwhash_str(
password,
sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE
);
}
deriveKeyFromPassword(password, salt) {
// Derive encryption key from password
return sodium.crypto_pwhash(
sodium.crypto_secretbox_KEYBYTES,
password,
salt,
sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
sodium.crypto_pwhash_ALG_DEFAULT
);
}
}
// Using Web Crypto API for browser-based encryption
class BrowserPrivacyEncryption {
async generateKey() {
return await crypto.subtle.generateKey(
{
name: 'AES-GCM',
length: 256
},
true, // extractable
['encrypt', 'decrypt']
);
}
async encryptData(data, key) {
const encoder = new TextEncoder();
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv
},
key,
encoder.encode(JSON.stringify(data))
);
return {
encrypted: btoa(String.fromCharCode(...new Uint8Array(encrypted))),
iv: btoa(String.fromCharCode(...iv))
};
}
async hashData(data) {
const encoder = new TextEncoder();
const hashBuffer = await crypto.subtle.digest(
'SHA-256',
encoder.encode(data)
);
return btoa(String.fromCharCode(...new Uint8Array(hashBuffer)));
}
}