简体   繁体   中英

How to convert SHA-256 Java to JavaScript( IONIC with NPM )?

I have given the below code in JAVA . I need to convert JavaScript like IONIC Framework .I tried IONIC App with NPM "crypto-js" and "js-sha256" . But, I couldn't identify the 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;

you can use crypto-js

check This Working Example

or

Install usin npm npm i js-sha256

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

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

then

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

using key

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

Yes.Finally I got a Answer :)

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

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

Method : 1 // js-sha256 - NPM

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

Method : 2 // node-forge - NPM

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM