Skip to content

Instantly share code, notes, and snippets.

@abhishekY495
Created November 11, 2022 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishekY495/e8c7989670fd118d78ba977b55fee5b9 to your computer and use it in GitHub Desktop.
Save abhishekY495/e8c7989670fd118d78ba977b55fee5b9 to your computer and use it in GitHub Desktop.
Encryption Code
const nodeCrypto = require("crypto");
const { Buffer } = require("buffer");
const app = {
encrypt: function (data, password) {
const salt = nodeCrypto.randomBytes(16);
const key = nodeCrypto.pbkdf2Sync(password, salt, 100000, 32, "sha256");
const cipher = nodeCrypto.createCipheriv("aes-256-gcm", key, salt);
const encryptedData = Buffer.concat([cipher.update(data), cipher.final()]);
const authTag = cipher.getAuthTag();
return Buffer.concat([salt, authTag, encryptedData]);
},
decrypt: function (data, password) {
try {
const salt = data.subarray(0, 16);
const authTag = data.subarray(16, 32);
const encData = data.subarray(32, data.length);
const key = nodeCrypto.pbkdf2Sync(password, salt, 100000, 32, "sha256");
const decipher = nodeCrypto.createDecipheriv("aes-256-gcm", key, salt);
decipher.setAuthTag(authTag);
const plainText = Buffer.concat([
decipher.update(encData),
decipher.final(),
]);
return plainText;
} catch (e) {
return true;
}
},
};
module.exports.app = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment