/home/techb158/balavpn.abdallabala.com/src/lib
Edit: /home/techb158/balavpn.abdallabala.com/src/lib/crypto.js (1676B)
const crypto = require("crypto");
function sha256(value, secret = "") {
return crypto.createHmac("sha256", secret || "cosmic-development-secret").update(String(value)).digest("hex");
}
function randomToken(bytes = 32) {
return crypto.randomBytes(bytes).toString("hex");
}
function redactToken(token) {
const value = String(token || "");
if (value.length <= 8) return "****";
return `${value.slice(0, 4)}...${value.slice(-4)}`;
}
function encryptionKey() {
return crypto
.createHash("sha256")
.update(process.env.COSMIC_TOKEN_ENCRYPTION_KEY || "cosmic-development-token-key")
.digest();
}
function encryptJson(payload) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", encryptionKey(), iv);
const plaintext = JSON.stringify(payload || {});
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return {
algorithm: "aes-256-gcm",
iv: iv.toString("base64"),
tag: tag.toString("base64"),
ciphertext: encrypted.toString("base64")
};
}
function decryptJson(payload) {
if (!payload) return {};
if (!payload.ciphertext || !payload.iv || !payload.tag) {
return payload;
}
const decipher = crypto.createDecipheriv("aes-256-gcm", encryptionKey(), Buffer.from(payload.iv, "base64"));
decipher.setAuthTag(Buffer.from(payload.tag, "base64"));
const decrypted = Buffer.concat([
decipher.update(Buffer.from(payload.ciphertext, "base64")),
decipher.final()
]);
return JSON.parse(decrypted.toString("utf8"));
}
module.exports = {
sha256,
randomToken,
redactToken,
encryptJson,
decryptJson
};