Converting SHA-256 from Java to JavaScript in an Ionic project using NPM: A step-by-step guide

In Java, I have a code snippet that needs to be converted into JavaScript using the Ionic Framework. I attempted to use Ionic App along with NPM packages like "crypto-js" and "js-sha256", but I was unable to find a suitable solution.

    String generatedPassword = null;
    String **SALTKEY** = 'mysecret';
    String inputPassword = 'mypassword';
    try {

         MessageDigest md = MessageDigest.getInstance("SHA-256");
         md.update(SALTKEY.getBytes());
         byte[] bytes = md.digest(inputPassword.getBytes());

         StringBuilder sb = new StringBuilder();
          for (int i = 0; i < bytes.length; i++) {
            sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
          }

      generatedPassword = sb.toString();

     } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
     }
     return generatedPassword;

Answer №1

One way to implement hashing is by utilizing the crypto-js library.

For a demonstration, refer to this Live Example

Alternatively,

To install, use npm and run npm i js-sha256

https://www.npmjs.com/package/js-sha256

import { sha256, sha224 } from 'js-sha256';

Then proceed with the following steps:

sha256('Your Message to hash');
sha224('Your Message to hash');

var yourHash = sha256.create();
yourHash.update('Message to hash');
yourHash.hex();

var yourHash2 = sha256.update('Message to hash');
yourHash2.update('Message2 to hash');
yourHash2.array();

Moreover, it's possible to incorporate a key for added security:

var hash = sha256.hmac.create('key');
hash.update('Message to hash');
hash.hex();

Answer №2

Finally, after searching high and low, I found the answer!

     import { sha256, sha224 } from 'js-sha256';
     import * as forge from 'node-forge';

     const SALTKEY = 'mysecret'; 
     const inputPassword = 'mypassword';

Method : 1 // Using js-sha256 NPM package

     var hash = sha256.create();
     hash.update(SALTKEY);
     hash.update(inputPassword);
     console.log(hash.hex());

Method : 2 // Utilizing node-forge NPM package

     var md = forge.md.sha256.create();
     md.update(SALTKEY);
     md.update(inputPassword);
     console.log(md.digest().toHex());

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

Adding or removing rows within an array in a hybrid Vue project - a step-by-step guide

Recently, I created a small web application to assist in organizing my project ideas. Check it out here: https://codepen.io/aibrindley/pen/ELXajM Now, I am working on enabling users to add items to the array directly from the interface. It would also be c ...

How can a number raised to the power of 10 be rounded to five decimal places?

When using Java for calculations, the results often come in a complex format such as "9.2233720368E11". My goal is to round this number to 5 decimals while preserving the power of 10 notation "E11". I attempted the following code: rounded = Math.round(su ...

Is it possible to turn off security features for a Heroku Postgres database?

My project doesn't involve sensitive data, so I'm not concerned about security vulnerabilities. I believe the issue lies in the connection between the App/server and the DB. I've searched on Youtube and Google for solutions, but the informa ...

AngularJS users are experiencing issues with the "See More" feature not functioning as expected

One of my tasks involves dealing with a block of text that needs to be truncated using ellipsis. To achieve this, I am utilizing jquery dotdotdot. For more information on dotdotdot, please refer to the documentation. I have created a straightforward dire ...

Encountering an issue with npm install when trying to add dependencies from a private Git

In my package.json file, there is an entry for "rtrk": "https://github.com/me/rtrk.git" under the dependencies. Until recently, running npm install or npm update rtrk commands worked fine. However, today, the npm install (update would ...

Tips for eliminating the left and bottom border in a React chart using Chart.js 2

Is there a way to eliminate the left and bottom borders as shown in the image? ...

Unable to choose anything within a draggable modal window

Can someone please assist me? I am struggling to figure this out. I can't select text inside the modal or click on the input to type text into it. I suspect it may be due to z-index issues, but I'm having trouble locating them. var currentZ = n ...

Encountering the "excessive re-renders" issue when transferring data through React Context

React Context i18n Implementation i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: { en: { translation: translationsEn }, bn: { translation: translationsBn }, }, lng: "bn ...

Impact of Jquery on dropdown menus in forms

Currently, I have a script for validating form information that adds a CSS class of .error (which includes a red border) and applies a shake effect when the input value is less than 1 character. Now, I also need to implement this validation on various sel ...

How to efficiently use promises within loops in JavaScript

I recently delved into Javascript and I'm still struggling with how promises work within loops. Currently, I am utilizing repl.it db for my project. Let's say I have an array consisting of keys, and my goal is to query each key in the array to st ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

Can Google Maps be initialized asynchronously without the need for a global callback function?

Currently, I am working on developing a reusable drop-in Module that can load Google Maps asynchronously and return a promise. If you want to take a look at the code I have constructed for this using AngularJS, you can find it here. One issue I have enco ...

Using the 'useMediaQuery' function from Material UI in a class component

Currently experimenting with Material UI's useMediaQuery feature to adjust the styles of a specific component, in this case the Button component. The objective is to eliminate the outline surrounding the button when the screen size decreases. The atte ...

Optimizing logical expressions in C++

Can I assume in C, C++, JavaScript, or any other modern language that if I have the following code snippet... bool funt1(void) {…} bool funt2(void) {…} if (funt1() && funt2()) {Some code} ...I am guaranteed that both functions will be called, ...

Is there a more efficient method to improve this Java code for generating a string from an ArrayList?

Currently, I am developing a Java scraping program using Selenium to extract data and store it in a database. While seeking ways to enhance my skill set, I have found that instructional videos do not hold my interest for long. I prefer hands-on learning ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

Setting individual state variables for each child component within a Vue loop

When I look at the code snippet below, I find myself facing an issue with state usage. <div class="featured-card-container"> <swiper class="swiper" :options="swiperOption"> <template v-fo ...

Substitute <br /> tags with a line separator within a textarea using JavaScript

Anyone have a quick fix for this? I've been searching online for a solution, but no luck so far. Already tried checking out: this, this Currently dealing with a textarea that receives data from AJAX call and it ends up looking like this: Hello& ...

Tips for maintaining focus on an editable div using jQuery

Is there a way to prevent an editable div from becoming unfocused when clicking on a formatting bar created using jQuery? I've been trying to implement this feature but can't seem to figure it out. Any advice would be greatly appreciated. Many th ...