I've been transitioning my code from node.js modules to web apis to try and port it to bowser and mobile, but I'm running into some performance issues.
The following code is for encrypting and decrypting text. Originally, it would take 1-2ms to do so using the crypto module, but using the webcrypto api each now takes about 30-60ms, which added on top of ping makes it a big problem. Does anybody know what I can do to further improve performance?
The following code is for encrypting and decrypting text. Originally, it would take 1-2ms to do so using the crypto module, but using the webcrypto api each now takes about 30-60ms, which added on top of ping makes it a big problem. Does anybody know what I can do to further improve performance?
JavaScript:
const textEncoder = new TextEncoder(); // Reuse encoder for performance
async function encrypt(text) {
if (!decodepass) return;
const textBytes = textEncoder.encode(text);
if (!keye) {
keye = await crypto.subtle.importKey(
'raw',
decodepass,
{ name: 'AES-CBC' },
false,
['encrypt']
);
}
try {
const encryptedBuffer = await crypto.subtle.encrypt(
{ name: 'AES-CBC', iv: decodeiv },
keye,
textBytes
);
const encryptedArray = new Uint8Array(encryptedBuffer);
let result = '';
for (let i = 0; i < encryptedArray.length; i += 0x8000) {
result += String.fromCharCode.apply(null, encryptedArray.subarray(i, i + 0x8000));
}
return result;
} catch (e) {
return null; // Return null on failure
}
}
const textDecoder = new TextDecoder('utf-8'); // Reuse decoder for performance
async function decrypt(text) {
if (!keyd) {
keyd = await crypto.subtle.importKey(
'raw',
decodepass,
{ name: 'AES-CBC' },
false,
['decrypt']
);
}
try {
const encryptedData = Uint8Array.from(text, c => c.charCodeAt(0));
const decryptedBuffer = await crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: decodeiv },
keyd,
encryptedData
);
return textDecoder.decode(decryptedBuffer);
} catch (e) {
return text; // fallback on error
}
}