PSA: Don’t use this. These are not “strong”: Anyone that knows the algorithm being used will be able to easily crack the encoded text.
You should instead use AES encryption (like AES-256-CBC) with a secure passphrase.
You can do it like this in node:
const crypto = require('crypto');
function encrypt(text, passphrase) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(passphrase, 'utf-8'), iv);
let encrypted = cipher.update(text, 'utf-8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decrypt(encryptedText, passphrase) {
const [ivHex, encrypted] = encryptedText.split(':');
const iv = Buffer.from(ivHex, 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(passphrase, 'utf-8'), iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf-8');
decrypted += decipher.final('utf-8');
return decrypted;
}
// Example
const passphrase = 'my_secret_passphrase';
const text = 'hii!';
const encrypted = encrypt(text, passphrase);
const decrypted = decrypt(encrypted, passphrase);
console.log('Encrypted:', encrypted);
console.log('Decrypted:', decrypted);
In the browser:
async function encrypt(text, passphrase) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(passphrase),
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encryptedData = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
data
);
return {
iv: Array.from(iv),
encryptedData: Array.from(new Uint8Array(encryptedData))
};
}
async function decrypt(encryptedObj, passphrase) {
const decoder = new TextDecoder();
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(passphrase),
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
const iv = new Uint8Array(encryptedObj.iv);
const encryptedData = new Uint8Array(encryptedObj.encryptedData);
const decryptedData = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
key,
encryptedData
);
return decoder.decode(decryptedData);
}
// example
const passphrase = 'my_secret_passphrase';
const text = 'hii!';
encrypt(text, passphrase).then(encrypted => {
console.log('Encrypted:', encrypted);
decrypt(encrypted, passphrase).then(decrypted => {
console.log('Decrypted:', decrypted);
});
});