Update the decryptresponse service

This commit is contained in:
ashutosh.nehete 2025-12-01 15:05:20 +05:30
parent cdff1888d8
commit 70992c9a46

View File

@ -1,47 +1,64 @@
// Helper to convert Base64 to ArrayBuffer import CryptoJS from 'crypto-js';
const base64ToArrayBuffer = (base64) => {
const binaryString = window.atob(base64); // The key from your C# Middleware
const len = binaryString.length; // In a real app, prefer storing this in process.env.REACT_APP_ENCRYPTION_KEY
const bytes = new Uint8Array(len); const KEY_BASE64 = "h9J4kL2mN5pQ8rS1tV3wX6yZ0aB7cD9eF1gH3jK5mN6=";
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i); /**
} * Decrypts the specific format sent by the C# EncryptionMiddleware.
return bytes.buffer; * Format: Base64([IV (16 bytes)] + [Encrypted Data])
}; * * @param {string} encryptedBase64Str - The raw response text from the API
* @returns {any} - The parsed JSON object or string
// Main Decryption Function */
export const decryptResponse = async (encryptedBase64) => { export const decryptResponse = (encryptedBase64Str) => {
const keyBase64 = "h9J4kL2mN5pQ8rS1tV3wX6yZ0aB7cD9eF1gH3jK5mN6="; // Same key try {
// 1. Parse the Key
// 1. Parse Key const key = CryptoJS.enc.Base64.parse(KEY_BASE64);
const keyBytes = base64ToArrayBuffer(keyBase64);
const key = await window.crypto.subtle.importKey( // 2. Parse the incoming Base64 string to a WordArray
"raw", const fullWordArray = CryptoJS.enc.Base64.parse(encryptedBase64Str);
keyBytes,
{ name: "AES-GCM" }, // 3. Convert to Hex to easily slice the IV (16 bytes = 32 hex chars)
false, // This is safer than manipulating WordArray indices directly
["decrypt"] const fullHex = CryptoJS.enc.Hex.stringify(fullWordArray);
);
// 4. Extract IV (First 16 bytes / 32 hex characters)
// 2. Parse Encrypted Data const ivHex = fullHex.substring(0, 32);
const encryptedBytes = new Uint8Array(base64ToArrayBuffer(encryptedBase64)); const iv = CryptoJS.enc.Hex.parse(ivHex);
// 3. Extract Parts (Nonce is first 12 bytes) // 5. Extract Ciphertext (The rest of the string)
const nonce = encryptedBytes.slice(0, 12); const cipherTextHex = fullHex.substring(32);
const ciphertextWithTag = encryptedBytes.slice(12); // Web Crypto expects Tag appended to Ciphertext const cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Hex.parse(cipherTextHex)
// 4. Decrypt });
try {
const decryptedBuffer = await window.crypto.subtle.decrypt( // 6. Decrypt
{ name: "AES-GCM", iv: nonce }, const decrypted = CryptoJS.AES.decrypt(
key, cipherParams,
ciphertextWithTag key,
); {
iv: iv,
const decoded = new TextDecoder().decode(decryptedBuffer); mode: CryptoJS.mode.CBC,
return JSON.parse(decoded); padding: CryptoJS.pad.Pkcs7
} catch (e) { }
console.error("Decryption failed:", e); );
return null;
} // 7. Convert to UTF-8 String
const decryptedString = decrypted.toString(CryptoJS.enc.Utf8);
if (!decryptedString) {
throw new Error("Decryption produced empty result (Wrong Key/IV?)");
}
// 8. Try to parse JSON, otherwise return plain string
try {
return JSON.parse(decryptedString);
} catch {
return decryptedString;
}
} catch (error) {
console.error("Decryption Failed:", error);
return null;
}
}; };