Need to create a SHA2 hash in c#

816 views Asked by At

I write a small program using the Vircurex API for trading e-currencies. Their documentation is using Ruby code examples and I am unsure of what the equivalent is in C#. For anyone interested, their documentation is listed here:

https://vircurex.com/welcome/api

I keep getting 8003 - Authentication failed, which I suppose means I send an incorrect SHA2 hash. They write that:

"A SHA2 hash across a number of input values. See below details on how to calculate it"

tok = Digest::SHA2.hexdigest("#{secret_word};#{user_name};#{t};#{trx_id};create_order;sell;10;btc;50;nmc")

I have the following code in c#:

    public static string getHashSha256(string text)
{
    byte[] bytes = Encoding.UTF8.GetBytes(text);
    SHA256Managed hashstring = new SHA256Managed();
    byte[] hash = hashstring.ComputeHash(bytes);
    string hashString = string.Empty;
    foreach (byte x in hash)
        hashString += String.Format("{0:x2}", x);

    return hashString;
}

I tried to test it in the online irb at

http://tryruby.org/levels/1/challenges/0

in order to see what hash the Digest::SHA2.hexdigest(".......") method would generate, but I get a

Digest::SH­A2.hexdige­st("hello"­)
=> #<NameError: uninitialized constant Digest>

So basically I don't know if it is an incorrect hash value, but I think it is. I would like to be able to test it in Ruby and also appreciate any help if there are errors in the way the C# method generates the hash.

2

There are 2 answers

0
Mauro Cerutti On

Given the same input string, your C# code and the call to Digest::SHA2.hexdigest() in Ruby should (and do, in my test) yield the same result. I don't think the problem lies in the way you are generating the hash.

0
Mustafa Chelik On
public static String sha256_hash(String value)
{
    StringBuilder Sb = new StringBuilder();

    using (SHA256 hash = SHA256Managed.Create())
    {
        Encoding enc = Encoding.UTF8;
        Byte[] result = hash.ComputeHash(enc.GetBytes(value));

        foreach (Byte b in result)
        {
            Sb.Append(b.ToString("x"));
        }
    }
    return Sb.ToString();
}