Mister 832
Mister 832

Reputation: 1221

Translate GetHashCode from VB to C#

I have to port some code from VB.net to C#. Now I'm quite embarassed, but I can't figuere out, how to translate the following code:

From VB

Dim Hash() As Byte
Hash = Encoding.UTF8.GetBytes("StackOverflow".GetHashCode)

To C# (not working):

byte[] Hash;
Hash = Encoding.UTF8.GetBytes("StackOverflow".GetHashCode());

What is the correct syntax?

Upvotes: 0

Views: 318

Answers (2)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22084

There are two problems with current approach.

A) Your problematic domain of possible passwords is int.MinValue to int.MaxValue (-2147483648 - 2147483647) i.e. 2^32, this means if this is exposed as web service and I can produce requests at pace say 10000 requests per second, it will take around 5 days (worst case) to brute-force guess password.

B) If your "hashed" passwords got ever stolen it will be very easy to reverse engineer passwords of your users since the default .NET string hashing function (https://github.com/floodyberry/Marvin32/blob/master/Marvin32.c) is not cryptographically strong (it is very fast - which is desirable for usage in hashtables and dictionaries, for which the GetHashCode() method is intended) - so random walking trough known password list will generate results with matching hashes FAST.

One might argue though that since you're not using well known cryptographic function, hacker will have to write some unique code to crack it and identify the hash function being used (that is without access to source code) - this is known as security through obscurity and true only for B)

Correct approach goes like:

var password = "StackOverflow";
// ideally salt should be something bound for given user
var salt = "MY UNIQUE SALT";
byte[] hash;
using (var algorithm = new SHA512Managed()) {
  hash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(salt + password));
}

Problematic domain of SHA512 is 2^512 - i.e. with requests at pace say 10000 per second it will take (4e+142 years) to crack it via brute-force. Plus since you're salting if your "hashed" passwords got ever stolen, it is impossible to reconstruct the original passwords.

So I'd recommend to implement a decent password hashing and force-switch users to new method.

Upvotes: 4

Damian
Damian

Reputation: 2852

Try

Hash = Encoding.UTF8.GetBytes("StackOverflow".GetHashCode().ToString());

For both C# and VB it gives the same result

Byte[] (11 items)
45 
50 
48 
51 
54 
49 
50 
54 
55 
56 
49 

Upvotes: 2

Related Questions