65 lines
1.6 KiB
TypeScript
65 lines
1.6 KiB
TypeScript
import { Service } from "typedi";
|
|
import { FrontendVariables } from "@Front/Config/VariablesFront";
|
|
import crypto from "crypto";
|
|
|
|
@Service()
|
|
export default class CryptoService {
|
|
private jwkKey: JsonWebKey;
|
|
private subtle: SubtleCrypto = window.crypto.subtle;
|
|
constructor(protected variables: FrontendVariables) {
|
|
this.jwkKey = {
|
|
kty: "oct",
|
|
k: variables.KEY_DATA,
|
|
alg: "A256GCM",
|
|
ext: true,
|
|
};
|
|
}
|
|
|
|
private async getKey() {
|
|
return await this.subtle.importKey("jwk", this.jwkKey, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
}
|
|
|
|
/**
|
|
* @description : encrypt data
|
|
* @throws {Error} If data cannot be encrypted
|
|
*/
|
|
public async encrypt(data: string) {
|
|
const encodedData = Buffer.from(data);
|
|
const iv = crypto.getRandomValues(new Uint8Array(16));
|
|
const key = await this.getKey();
|
|
const cipherData = await this.subtle.encrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv,
|
|
},
|
|
key,
|
|
encodedData,
|
|
);
|
|
|
|
const cipherText = Buffer.from(cipherData).toString("base64");
|
|
const ivStringified = Buffer.from(iv).toString("base64");
|
|
|
|
return { cipherText, ivStringified };
|
|
}
|
|
|
|
/**
|
|
* @description : decrypt data with an initialization vector
|
|
* @throws {Error} If data cannot be decrypted
|
|
*/
|
|
public async decrypt(cipherText: string, ivStringified: string): Promise<string> {
|
|
const cipherData = Buffer.from(cipherText, "base64");
|
|
const iv = Buffer.from(ivStringified, "base64");
|
|
const key = await this.getKey();
|
|
const decryptedData = await this.subtle.decrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv,
|
|
},
|
|
key,
|
|
cipherData,
|
|
);
|
|
|
|
return Buffer.from(decryptedData).toString("utf-8");
|
|
}
|
|
}
|