I am facing an issue with storing encrypted data in a string format. I have tried using the TextEncoder method but it seems to be creating strings with different bytes compared to the original ArrayBuffer.
Here is the line causing the problem:
const str = new TextEncoder().encode(buff1);
Instead of producing similar byte lengths as the original ArrayBuffer, this code results in:
ArrayBuffer { byteLength: 139 }
ArrayBuffer { byteLength: 262 }
This inconsistency is puzzling as they should ideally match. Despite trying various alternatives, I have not been able to rectify this issue. If anyone could provide guidance on fixing this, it would be greatly appreciated.
Note that while the EncryptText function functions correctly, it has been included for reference purposes when running the code in IDEs.
async function encryptText(plainText, iv, password): Promise<ArrayBuffer> {
const ptUtf8 = new TextEncoder().encode(plainText);
const pwUtf8 = new TextEncoder().encode(password);
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
const alg = { name: 'AES-GCM', iv: iv };
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);
return crypto.subtle.encrypt(alg, key, ptUtf8);
};
async function encrBuffToUtf8Test() {
const plainData = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, ' +
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
const password = 'infamous';
const randomValues = crypto.getRandomValues(new Uint8Array(12));
const encryptionResult1 = await this.encryptText(plainData, randomValues, password);
const buff1 = Buffer.from(encryptionResult1);
const str = new TextEncoder().encode(buff1);
const utf8buff = new TextDecoder('utf-8').decode(buff);
const encryptionResult2 = utf8buff.buffer;
const resTest = encryptionResult1 === encryptionResult2;
if (!resTest) {
console.log(encryptionResult1);
console.log(encryptionResult2);
}
}