简体   繁体   中英

Hashing in python and javascript returning different results

I have some legacy python script to one way encrypt passwords for db storage

import base64, hashlib

def encrypt(passw):

    secret = "SECRET_KEY_HERE"
    passw = secret + passw
    passw = passw.encode('utf-8')
    m = hashlib.sha256()
    m.update(passw)
    encoded = base64.b64encode(m.digest()).decode('utf-8')
    return (encoded)

I managed to put together a c# version for an existing 3rd party package we are using

private static string Encrypt(string clearText)
        {
            SHA256 sHA256 = SHA256.Create();

            byte[] sourceArray = sHA256.ComputeHash(Encoding.UTF8.GetBytes(EncryptionKey + clearText));

            return Convert.ToBase64String(sourceArray);
        }

These both return the same results. I am trying to put together a web front end using next and have added an encrypt function to the register / login page

const crypto = require('crypto');

export const encrypt = (password: string) :string => {
    const key = process.env.PASS_KEY;
    return crypto.createHash('sha256').update(key + password).digest('base64')  
}

this returns a different result to the other two functions.

I have checked all the usual sources and all that I have found is that what I have put together should work fine.

Can anyone please shed any light on why this is not working

UPDATE:

Just to add to my confusion, I added the js function to a react form in codesandbox and it returns the correct result.

The function is currently only called via the nextauth authorize function to verify the login of a user like this

const confirmPasswordHash = (plainPassword: string , hashedPassword: string) => {
    
        const res = plainPassword && hashedPassword.localeCompare(encrypt(plainPassword))
        return res === 0 ? true:false
    
}

Jonathan Ciapetti pointed me in the right direction to solve this. The problem did indeed lie within the process.env call.

The key being used includes a dollar sign which was, in turn, truncating part of the string being passed in. I solved this be escaping the dollar sign in the key and now it all works as expected.

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