Transforming encoded information into a text format and then reversing the process

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);
    }
}

Answer №1

It seems like I find myself repeating this answer on a daily basis, but once again, it's not possible to convert random binary data into a string using standard character encodings. It just doesn't function in that manner.

Perhaps you should opt for base64 or hex instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I import NPM modules in Angular 5 without using @types?

Currently experimenting with Angular 5 and beginning a project from angular-cli. I am interested in incorporating a NPM module called J2M (https://github.com/kylefarris/J2M). During my research, I came across these two commands: npm install j2m --save npm ...

Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React. Environment Frontend TypeScript React AWS Amplify (for API module) Backend(AWS Lambda) Node.js Expecta ...

What is the best method for managing an event loop during nested or recursive calculations?

When it comes to breaking a computation and releasing using setTimeout(), most examples seen involve having a shallow call stack. But what about scenarios where the computation is deeply nested or mutually-recursive, like in a tree search, with plenty of c ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Best practice for saving a User object to the Request in a Nest.js middleware

Currently, in my nest.js application, I have implemented a middleware to authenticate Firebase tokens and map the user_id to my database. Within this middleware, I retrieve the user_id from Firebase, fetch the corresponding User object from the database, a ...

iterating through the checked values in Angular 4

I need assistance in writing a loop using TypeScript to send each checked employee as a parameter to the postCouncilAbsence function. Can anyone help? component.ts: onattendanceSave(form:NgForm){ this.index = this.attendanceForm.value console.log ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

Is it possible to encounter an unusual token export while trying to deactivate Vue with veevalidate

Utilizing Nuxt with server side rendering. Incorporating Typescript along with vee-validate version 3.4.9. The following code has been validated successfully extend('positive', value => { return value >= 0; }); Upon adding the default, ...

Tips for referencing functions in TypeScript code

In regard to the function getCards, how can a type be declared for the input of memoize? The input is a reference to a function. import memoize from "fast-memoize"; function getCards<T>( filterBy: string, CardsList: T[] = CardsJSON.map((item, i ...

Select specific columns from an array using Typescript

I have a collection of objects and I'm looking for a way to empower the user to choose which attributes they want to import into the database. Is there a method to map and generate a separate array containing only the selected properties for insertion ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

What is the reason for the function to return 'undefined' when the variable already holds the accurate result?

I have created a function that aims to calculate the digital root of a given number. Despite my efforts, I am encountering an issue where this function consistently returns undefined, even though the variable does hold the correct result. Can you help me ...

For Angular 4, simply add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of the component in order to permit any element

After using angular-cli to create a new project (ng new my-project-name), I ran npm run test successfully without any issues. To display font icons in my project, I added the Font Awesome module from https://www.npmjs.com/package/angular-font-awesome. In ...

What methods are available to restrict the values of properties to specific keys within the current type?

I am looking to declare an interface in typescript that is extensible through an indexer, allowing for the dynamic association of additional functions. However, I also want sub properties within this interface that can refer back to those indexed functio ...

How come I am unable to fetch classes and enums from a namespace?

When using Typescript with pg-promise, I am facing an issue where I can't import the classes and enums as I normally would. Typically, when working with a library, I import a type, use it, and everything functions properly. However, in the snippet bel ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

NodeJS on Cloudlinux requires that the node modules for applications be stored in a distinct folder (virtual environment) designated by a symbolic link known as "node_modules"

I recently encountered an issue while trying to deploy my Nodejs/TypeScript web application on my cpanel shared hosting. The error I received stated: * Cloudlinux NodeJS Selector requires the node modules for the application to be stored in a separate f ...

Why do I keep getting an ExpressionChangedAfterItHasBeenChecked error after trying to update a random color in an

Is there a way to assign a random color from an array without causing the error message: "ExpressionChangedAfterItHasBeenChecked"? Even though the color of the chip changes quickly before the message appears, it seems like it's working. How can I reso ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

Using path aliases in a Typescript project with Typescript + Jest is not a viable option

Note I am able to use aliases in my TypeScript file. Unfortunately, I cannot use aliases in my test files (*.test.ts). My Configuration 1. Jest.config.ts import type { Config } from '@jest/types'; const config: Config.InitialOptions = { ve ...