Reputation: 10634
Given the following c# code.
public static string HashSHA512( string phrase )
{
if( m_SHA512HashProvider == null )
m_SHA512HashProvider = new SHA512CryptoServiceProvider();
if ( m_HashBuffer == null )
m_HashBuffer = new byte[512];
int length = Encoding.ASCII.GetBytes( phrase, 0, phrase.Length > 512 ? 512 : phrase.Length, m_HashBuffer, 0 );
byte[] hashed = m_SHA512HashProvider.ComputeHash( m_HashBuffer, 0, length );
return BitConverter.ToString( hashed );
}
and the following nodejs code
generate: function(input, cb){
var hash = Crypto.createHash('sha512').update(input).digest('hex');
console.log('crypto generate:', hash);
return cb(hash);
},
my hashes don't match up. How can I alter either side to make them match up accordingly?
Upvotes: 1
Views: 1806
Reputation: 24395
There are multiple errors in your C# code.
Compare the following and try to figure out exactly where the faults are.
public static string HashSHA512( string phrase )
{
if( m_SHA512HashProvider == null )
m_SHA512HashProvider = new SHA512CryptoServiceProvider();
byte[] hashed = m_SHA512HashProvider.ComputeHash(Encoding.UTF8.GetBytes(phrase)); // or ASCII if that's sufficient for you input data.
return BitConverter.ToString( hashed );
}
Some hints:
UTF8
instead of ASCII
(some characters might get truncated)GetBytes
doesn't return a length of something. It returns an array of bytes.ComputeHash
doesn't have an out
or ref
parameter and since m_HashBuffer
contains nothing, if m_HashBuffer
is null, the hash is always computed on nothing.Edit
Looking at the node.js API it seems that in C# you need to do an additional step:
return BitConverter.ToString(hashed).Replace("-", "").ToLower();
This is because the digest
method doesn't add the hyphens and all characters are lower case.
Disclaimer: Code not tested.
Upvotes: 4