简体   繁体   中英

Javascript equivalent to C# SHA512

I'm having trouble converting this C# function that takes in input and converts it to hash and returns a byte array, to Javascript.

    public static byte[] Sha512(string input)
    {
        using (SHA512 sha = new SHA512Managed())
        {
            return sha.ComputeHash(Encoding.UTF8.GetBytes(input));
        }
    }

Input in this example is: "1pImY_gls.hu". The C# function correctly returns:

[57, 115, 234, 22, 47, 82, 252, 77, 133, 181, 138, 214, 32, 3, 155, 216, 181, 246, 130, 106, 160, 198, 73, 110, 50, 68, 56, 18, 120, 152, 231, 55, 3, 14, 144, 21, 84, 92, 237, 190, 6, 124, 51, 221, 95, 195, 73, 168, 100, 167, 84, 185, 167, 142, 184, 72, 243, 120, 213, 64, 176, 215, 15, 25]

My current Javascript function converts the input to:

[51, 57, 55, 51, 101, 97, 49, 54, 50, 102, 53, 50, 102, 99, 52, 100, 56, 53, 98, 53, 56, 97, 100, 54, 50, 48, 48, 51, 57, 98, 100, 56, 98, 53, 102, 54, 56, 50, 54, 97, 97, 48, 99, 54, 52, 57, 54, 101, 51, 50, 52, 52, 51, 56, 49, 50, 55, 56, 57, 56, 101, 55, 51, 55, 48, 51, 48, 101, 57, 48, 49, 53, 53, 52, 53, 99, 101, 100, 98, 101, 48, 54, 55, 99, 51, 51, 100, 100, 53, 102, 99, 51, 52, 57, 97, 56, 54, 52, 97, 55, 53, 52, 98, 57, 97, 55, 56, 101, 98, 56, 52, 56, 102, 51, 55, 56, 100, 53, 52, 48, 98, 48, 100, 55, 48, 102, 49, 57]

I'm fairly new to encoding so I'm not sure how I should proceed. In this example I'm using crypto but I have no problem using crypto-js instead. My current Javascript function is:

    convertPassword: function(password){
        convertPassword: function(password){
        var encoder = new TextEncoder()

        var sha512 = crypto.createHash('sha512').update(password).digest("hex")
        
        return encoder.encode(sha512)
    },

In C# code you are digesting your hashed password in "latin1" charset encoding. In your node.js code, you've set it to digest in HEX. You need to change that to "latin1" and your problem should be solved. So in order to have the same output...

This line:

var sha512 = crypto.createHash('sha512').update(password).digest("hex")

Should look like this:

var sha512 = crypto.createHash('sha512').update(password).digest("latin1")

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