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

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Guide: Reversing a Number from 001 to 100 in Python

Example Input: 001 Example Output: 100 I've been experimenting with this code, but unfortunately it's not producing the desired result. Can someone please assist me? x = int(input()) s = str(x) reversed_string = s[::-1] print(rever ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

Using Regular Expressions: Ensuring that a specific character is immediately followed by one or multiple digits

Check out the regular expression I created: ^[0-9\(\)\*\+\/\-\sd]*$ This regex is designed to match patterns such as: '2d6', '(3d6) + 3', and more. However, it also mistakenly matches: '3d&apos ...

A guide on specifying the data type for functions that receive input from React Child components in TypeScript

Currently, I am faced with the task of determining the appropriate type for a function that I have created in a Parent Component to retrieve data from my Child Component. Initially, I resorted to using type: any as a solution, although it was not the corr ...

Is it possible to verify if a boolean value is false within each object in an array?

I am working with an array that contains multiple objects. Each object has a 'Position' and 'Mandatory' field: quesListArray = [ {Position: 1, Mandatory: false}, {Position: 2, Mandatory: true}, ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

Typescript function incorrectly returns Protractor's "element.all" output as Promise<string> instead of Promise<string[]>

Kindly review the code snippet provided below. The function getAllGroupIds() is designed to return an array of IDs belonging to "group" elements. The goal is to retrieve all the group-ids both before and after a test action, in order to compare them. Howe ...

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

Is importing all models into every component considered poor practice?

At my workplace, there is a practice in the legacy code where every single model is imported into all components, regardless of whether they are needed or not. For example: import * as models from '../../view-models/models' ....... let parrot: m ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

Using ts-node-dev (and ts-node) with ECMAScript exports and modules

Currently, we are in the process of upgrading TypeScript to a more modern standard due to changes in libraries like nanoid that no longer support commonjs exports. Our goal is to integrate the ts-node-dev library with exporting to ECMAScript modules. The ...

What is the process for finding GitHub users with a specific string in their name by utilizing the GitHub API

I'm looking to retrieve a list of users whose usernames contain the specific string I provide in my query. The only method I currently know to access user information is through another endpoint provided by the GitHub API, which unfortunately limits t ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

Typescript offers a feature where we can return the proper type from a generic function that is constrained by a lookup type,

Imagine we have the following function implementation: type Action = 'GREET' |'ASK' function getUnion<T extends Action>(action: T) { switch (action) { case 'GREET': return {hello: &a ...

Why is the Routes module failing to acknowledge the component?

I am in the process of developing my own Portfolio and decided to use Angular 12. Despite following all of the instructions on angular.io, I am facing challenges with Routing. To demonstrate my work more effectively, I have created a Stack Blitz: My Portf ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

TypeScript failing to infer type from return value of class method

Currently, I am developing a class where the constructor calls one of its methods toJSON and sets the return value to an instance property: class Example { property; snapshot; constructor(){ this.property = 'property' if (Math.ran ...

Attempting to perform an API invocation on a distant endpoint utilizing NestJS

var unirest = require("unirest"); var req = unirest("GET", "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data"); req.query({ "ingr": "1 large apple" }); req.headers({ &qu ...

What distinguishes Angular directives as classes rather than functions?

When using Ng directives within HTML tags (view), they appear to resemble functions that are called upon rather than instances of a class. It almost feels like they could be static methods that can be invoked without an instance of a class. Comin ...