Search code examples
node.jssha256sha

define hash cod SHA256 NodeJS


How to select the hash code on NodeJS?

I have a system made in another language with passwords on SHA256

The function there is:

#define HASH_CODE = 'WEASDSAEWEWAEAWEAWEWA';
SHA256_PassHash(HASH_CODE, password, 64);

First, param is the hash code, second is the var will be encrypted, third is the base64

I made the encrypt on NodeJS, but I have no control on hash code, so the systems don't make the same hash, how to select the code on the register on NodeJS so the system communicates with others?

const code = 'WEASDSAEWEWAEAWEAWEWA';
const normal = 'anne';
const crypto = require('crypto');
const encrypted = crypto
     .createHash('sha256')
     .update(normal)
     .digest('base64');
console.log(encrypted);

A exemple of compatibly code, this login on PHP login.php

<?php require_once('../mysql_conn.php'); ?> 
    <?php
    session_start();
    $HASH_SENHA = 'WEASDSAEWEWAEAWEAWEWA';

    if(isset($_SESSION['Username']))
    {
        header("location: ../myaccount.php");
        exit();
    } 
    if(isset($_POST['usr']) && isset($_POST['psw']) && isset($_POST['botao'])) 
    { 
        $usuario = mysqli_real_escape_string($MYSQL_CONNECT, $_POST['usr']);  
        $senha = strtoupper(hash("sha256", $_POST['psw'] . $HASH_SENHA));  
        $query = mysqli_query($MYSQL_CONNECT, "SELECT * FROM accounts WHERE Username='$usuario' AND Senha='$senha' LIMIT 1");  

        if(mysqli_num_rows($query) < 1)  
        {
            echo "<script type=\"text/javascript\">
                        alert('Incorrect Username or Password.');
                        window.location = '../login.php';
                  </script>";
            exit();
        }
        else 
        {
            //login efetuado 
            $dados = mysqli_fetch_assoc($query);  


            if (isset($_SESSION['loc'])) {
                header("location:".$_SESSION['loc']);
            }
            else header("location:../index.php");

        }  
    }
    ?> 

Solution

  • By looking at the PHP code you've provided.

    hash("sha256", $_POST['psw'] . $HASH_SENHA)
    

    It's hashing the string concatenation of $_POST['psw'] and $HASH_SENHA

    So, the equivalent code in Node.js should look like below

    Node.js

    const crypto = require('crypto');
    const code = 'WEASDSAEWEWAEAWEAWEWA';
    const input = 'password 123';
    
    const encrypted = crypto
         .createHash('sha256')
         .update(input + code)  // concatenation
         .digest('hex');        // get hash in hex format
    
    console.log(encrypted);
    

    Output

    3b3107f01da624da6bb014abe532aa7416869811ebe321784b26770cd2dd74ff