In Node.js, encryption techniques are primarily implemented using the built-in crypto module, which offers functionalities such as encryption, decryption, signing, and verification. The following are common usage scenarios:
1. Data Encryption and Decryption
The crypto module in Node.js can be used for encrypting and decrypting data. It supports both symmetric encryption (using the same key for both encryption and decryption) and asymmetric encryption (using a public key for encryption and a private key for decryption).
Example: Symmetric Encryption
javascriptconst crypto = require('crypto'); const algorithm = 'aes-256-cbc'; const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16); function encrypt(text) { let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }; } function decrypt(text) { let iv = Buffer.from(text.iv, 'hex'); let encryptedText = Buffer.from(text.encryptedData, 'hex'); let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv); let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString(); } // Test encryption and decryption const text = "Hello Node.js"; const encrypted = encrypt(text); console.log(encrypted); const decrypted = decrypt(encrypted); console.log(decrypted);
2. Hash Calculation
Hash calculation is used to compute data hashes, commonly for verifying data integrity, such as file hashes or password storage.
Example: Calculating Hashes
javascriptconst crypto = require('crypto'); function hash(data, algorithm = 'sha256') { return crypto.createHash(algorithm).update(data).digest('hex'); } const data = 'Hello Node.js'; console.log(hash(data)); // Output the SHA256 hash of the data
3. Digital Signatures and Verification
Digital signatures are generated using a private key and verified using a public key. This is crucial for secure network communications and data transmission.
Example: Digital Signatures and Verification
javascriptconst crypto = require('crypto'); const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, }); function sign(data, privateKey) { const sign = crypto.createSign('SHA256'); sign.update(data); sign.end(); return sign.sign(privateKey, 'hex'); } function verify(data, signature, publicKey) { const verify = crypto.createVerify('SHA256'); verify.update(data); verify.end(); return verify.verify(publicKey, signature, 'hex'); } const data = 'Hello Node.js'; const signature = sign(data, privateKey); console.log('Signature:', signature); const isValid = verify(data, signature, publicKey); console.log('Is valid:', isValid);
These functionalities demonstrate Node.js's capability in handling security and data protection, widely applied in systems and applications requiring security.