can-algorithm
Version:
Cortex Algorithm Numeral - Intelligent development automation tool
76 lines (59 loc) • 2.37 kB
JavaScript
import crypto from 'crypto';
import CryptoJS from 'crypto-js';
import os from 'os';
const ALGORITHM = 'aes-256-gcm';
const SALT_LENGTH = 64;
const TAG_LENGTH = 16;
const IV_LENGTH = 16;
const KEY_LENGTH = 32;
const ITERATIONS = 100000;
function deriveKey(password, salt) {
return crypto.pbkdf2Sync(password, salt, ITERATIONS, KEY_LENGTH, 'sha256');
}
export function encrypt(text, password = getSystemKey()) {
const salt = crypto.randomBytes(SALT_LENGTH);
const iv = crypto.randomBytes(IV_LENGTH);
const key = deriveKey(password, salt);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
const encrypted = Buffer.concat([
cipher.update(text, 'utf8'),
cipher.final()
]);
const tag = cipher.getAuthTag();
return Buffer.concat([
salt,
iv,
tag,
encrypted
]).toString('base64');
}
export function decrypt(encryptedData, password = getSystemKey()) {
const buffer = Buffer.from(encryptedData, 'base64');
const salt = buffer.slice(0, SALT_LENGTH);
const iv = buffer.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
const tag = buffer.slice(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
const encrypted = buffer.slice(SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
const key = deriveKey(password, salt);
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([
decipher.update(encrypted),
decipher.final()
]);
return decrypted.toString('utf8');
}
function getSystemKey() {
const systemInfo = `${os.hostname()}-${os.platform()}-${os.arch()}`;
return crypto.createHash('sha256').update(systemInfo).digest('hex').substring(0, 32);
}
export function hashPassword(password) {
return crypto.createHash('sha256').update(password).digest('hex');
}
export function obfuscateCode(code) {
const obfuscated = CryptoJS.AES.encrypt(code, getSystemKey()).toString();
return Buffer.from(obfuscated).toString('base64');
}
export function deobfuscateCode(obfuscated) {
const encrypted = Buffer.from(obfuscated, 'base64').toString();
return CryptoJS.AES.decrypt(encrypted, getSystemKey()).toString(CryptoJS.enc.Utf8);
}