@azure/static-web-apps-cli
Version:
Azure Static Web Apps CLI
73 lines • 3.04 kB
JavaScript
import crypto from "node:crypto";
import { logger } from "../../utils/logger.js";
export class CryptoService {
machineId;
static IV_LENGTH = 16; // For AES, this is always 16
static ALGORITHM = "aes-256-cbc";
encryption;
constructor(machineId) {
this.machineId = machineId;
logger.silly(`Invoking crypto service`);
}
getEncryption() {
if (!this.encryption) {
this.encryption = Promise.resolve({
encrypt: (machineId, value) => {
return new Promise((resolve, reject) => {
try {
const iv = crypto.randomBytes(CryptoService.IV_LENGTH);
let cipher = crypto.createCipheriv(CryptoService.ALGORITHM, Buffer.from(machineId), iv);
let encrypted = cipher.update(value);
encrypted = Buffer.concat([encrypted, cipher.final()]);
const encryptedValue = iv.toString("hex") + ":" + encrypted.toString("hex");
resolve(encryptedValue);
}
catch (error) {
reject(error);
}
});
},
decrypt: (machineId, data) => {
return new Promise((resolve, reject) => {
try {
let dataSegments = data.includes(":") ? data.split(":") : [];
let iv = Buffer.from(dataSegments.shift() || "", "hex");
let encryptedText = Buffer.from(dataSegments.join(":"), "hex");
let decipher = crypto.createDecipheriv(CryptoService.ALGORITHM, Buffer.from(machineId), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
resolve(decrypted.toString());
}
catch (error) {
reject(error);
}
});
},
});
}
return this.encryption;
}
async encrypt(value) {
logger.silly(`Encrypting credentials`);
try {
const encryption = await this.getEncryption();
return encryption.encrypt(this.machineId, value);
}
catch (error) {
logger.warn(`Failed to encrypt credentials: ${error.message}`);
return value;
}
}
async decrypt(value) {
logger.silly(`Decrypting credentials`);
try {
const encryption = await this.getEncryption();
return encryption.decrypt(this.machineId, value);
}
catch (error) {
logger.warn(`Failed to decrypt credentials: ${error.message}`);
return value;
}
}
}
//# sourceMappingURL=crypto.js.map