Encryption converts plain text into cipher-text using cryptographic algorithms , the main purpose of encryption is to maintain confidentiality .
Some of the common encryption algorithms are :
1.AES
2. RSA
3.ECC
Encryption is a two way process , what encrypted can be decrypted with a proper key .
However this is different to hashing where a mathematical operation is performed on it to get the output , this mathematical operation generally performed according to the hash function .
To implement AES in nodejs you have crypto module that can be used to encrypt and decrypt .
import { createCipheriv, randomBytes, scrypt } from 'crypto';
import { promisify } from 'util';
const iv = randomBytes(16);
const password = 'encryptpassword'; //password which would be used
key length depends on the algorithm for aes256 , it is 23 bytes
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
const cipher = createCipheriv('aes-256-ctr', key, iv);
const textToEncrypt = 'kasyap';
const encryptedText = Buffer.concat([
cipher.update(textToEncrypt),
cipher.final(),
]);
textToEncrypt contains the text which needs to be encrypted .
now textToEncrypt will be encrypted and stored in encryptedText variable.
In order to decrypt,
import { createDecipheriv } from 'crypto';
const decipher = createDecipheriv('aes-256-ctr', key, iv);
const decryptedText = Buffer.concat([
decipher.update(encryptedText),
decipher.final(),
]);
Hashing
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 'd0/\/\P5$$w0rD';
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
// now we might use a function to compare whether the hashed password and the the myPlaintextPassword are same .
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
Hashing is generally done to securely store passwords in the database.