Unauthenticated Requests
const cryptoObj = typeof window !== "undefined" ? window.crypto : crypto;
export const generateAesKey = async () => {
const cryptoKey = await cryptoObj.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"]
);
return await cryptoObj.subtle.exportKey("raw", cryptoKey);
};const encrypt = async (algo, key, data) => {
try {
const encryptedResult = await cryptoObj.subtle.encrypt(algo, key, data);
return encryptedResult;
} catch (error) {
console.error("Encryption error:", error);
throw error;
}
};
const rsaEncrypt = async (
plainText: string,
encryptionKey: BufferSource,
keyFormat: "spki" = "spki",
hashName: "SHA-256" = "SHA-256"
) => {
if (!encryptionKey) {
throw Error("Encryption key not initialized");
}
const encoder = new TextEncoder();
const data = encoder.encode(plainText);
let cryptoKey: CryptoKey;
let encrypted: ArrayBuffer;
try {
cryptoKey = await importKey(
keyFormat,
encryptionKey,
{ name: "RSA-OAEP", hash: { name: hashName } },
["encrypt"]
);
encrypted = await encrypt({ name: "RSA-OAEP" }, cryptoKey, data);
return btoa(String.fromCharCode.apply(null, new Uint8Array(encrypted)));
} catch (error) {
console.error("RSA-OAEP Encryption error:", error);
throw error;
}
};
export const aesEncrypt = async (
plainText: string,
encryptionKey: BufferSource,
keyFormat: "raw" = "raw",
keyLength: number = 256
) => {
if (!encryptionKey) {
throw Error("Encryption key not initialized");
}
const encoder = new TextEncoder();
const data = encoder.encode(plainText);
let cryptoKey: CryptoKey;
let encrypted: ArrayBuffer;
try {
cryptoKey = await importKey(keyFormat, encryptionKey, { name: "AES-GCM", length: keyLength }, [
"encrypt",
]);
const iv = cryptoObj.getRandomValues(new Uint8Array(12)); // Initialization vector
encrypted = await encrypt({ name: "AES-GCM", iv }, cryptoKey, data);
const combined = new Uint8Array(iv.length + encrypted.byteLength);
combined.set(iv, 0);
combined.set(new Uint8Array(encrypted), iv.length);
return btoa(String.fromCharCode.apply(null, combined));
} catch (error) {
console.error("AES-GCM Encryption error:", error);
throw error;
}
};
Last updated