interface EncryptedData {
iv: string; // Hex string
encryptedData: string; // Hex string
}
async function decrypt(encryptedObject: EncryptedData, secretKeyHex: string): Promise<string> {
// Utility function to convert hex string to Uint8Array
const hexToUint8Array = (hexString: string): Uint8Array => {
const length = hexString.length / 2;
const uintArray = new Uint8Array(length);
for (let i = 0; i < length; i++) {
uintArray[i] = parseInt(hexString.substr(i * 2, 2), 16);
}
return uintArray;
};
// Convert encrypted data and IV from hex strings to Uint8Array
const iv = hexToUint8Array(encryptedObject.iv);
const encryptedData = hexToUint8Array(encryptedObject.encryptedData);
// Assuming the secret key is provided in hex and needs to be converted
const rawKey = hexToUint8Array(secretKeyHex);
// Import the key into the Web Crypto API
const cryptoKey = await crypto.subtle.importKey(
'raw',
rawKey,
{ name: 'AES-CBC', length: 256 } as AesKeyAlgorithm,
false,
['decrypt']
);
// Decrypt the data
const decryptedData = await crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: iv } as AesCbcParams,
cryptoKey,
encryptedData
);
// Convert the decrypted array buffer back to a string
const decoder = new TextDecoder();
return decoder.decode(decryptedData);
}
// Example usage:
// Assuming you have encryptedObject and secretKeyHex defined elsewhere
// decrypt(encryptedObject, secretKeyHex).then((decryptedText) => {
// console.log(decryptedText);
// });
interface EncryptedData {
iv: string; // Hex string
encryptedData: string; // Hex string
}
async function decrypt(encryptedObject: EncryptedData, secretKeyHex: string): Promise<string> {
// Utility function to convert hex string to Uint8Array
const hexToUint8Array = (hexString: string): Uint8Array => {
const length = hexString.length / 2;
const uintArray = new Uint8Array(length);
for (let i = 0; i < length; i++) {
uintArray[i] = parseInt(hexString.substr(i * 2, 2), 16);
}
return uintArray;
};
// Convert encrypted data and IV from hex strings to Uint8Array
const iv = hexToUint8Array(encryptedObject.iv);
const encryptedData = hexToUint8Array(encryptedObject.encryptedData);
// Assuming the secret key is provided in hex and needs to be converted
const rawKey = hexToUint8Array(secretKeyHex);
// Import the key into the Web Crypto API
const cryptoKey = await crypto.subtle.importKey(
'raw',
rawKey,
{ name: 'AES-CBC', length: 256 } as AesKeyAlgorithm,
false,
['decrypt']
);
// Decrypt the data
const decryptedData = await crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: iv } as AesCbcParams,
cryptoKey,
encryptedData
);
// Convert the decrypted array buffer back to a string
const decoder = new TextDecoder();
return decoder.decode(decryptedData);
}
// Example usage:
// Assuming you have encryptedObject and secretKeyHex defined elsewhere
// decrypt(encryptedObject, secretKeyHex).then((decryptedText) => {
// console.log(decryptedText);
// });