views:

50

answers:

2

hello, I was wondering if someone could help me to get this method converted to ruby, is this possible at all?

public static string getSHA512(string str){
    UnicodeEncoding UE = new UnicodeEncoding();
    byte[] HashValue = null;
    byte[] MessageBytes = UE.GetBytes(str);
    System.Security.Cryptography.SHA512Managed SHhash = new System.Security.Cryptography.SHA512Managed();
    string strHex = "";
    HashValue = SHhash.ComputeHash(MessageBytes);
    foreach (byte b in HashValue){
        strHex += string.Format("{0:x2}", b);
    }
    return strHex;
}

Thanks in advance


UPDATE:

I just would like to make it clear that unfortunately it's method is not just for SHA512 generation but a custom one. I believe that the Digest::SHA512.hexdigest would be just the SHHast instance, but if you carefully look for the method you can see that it differs a bit from a simple hash generation. Follows the result of both functions.

# in C#
getSHA512("hello") => "5165d592a6afe59f80d07436e35bd513b3055429916400a16c1adfa499c5a8ce03a370acdd4dc787d04350473bea71ea8345748578fc63ac91f8f95b6c140b93"

# in Ruby
Digest::SHA512.hexdigest("hello") || Digest::SHA2 => "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043" 
A: 

Use the Digest::SHA2 class.

Sjoerd
hi Sjoerd I'm afraid I already used Digest::SHA512.digest but I have no clue on how to use the other classes in there, like UnicodeEncoding, GetBytes, ComputeHash :( . On this method the Digest::SHA512.digest would be just the SHhash instance.
ludicco
+3  A: 
Jörg W Mittag
Hi Jörg, unfortunately it's not so simple :( this is just the SHhash instance as Sjoerd recommended too.I've updated my question with the examples. So you can see the difference between them :)
ludicco
@ludicco: Sorry, I missed the fact that you are transcoding to UTF-16LE first. Fixed now.
Jörg W Mittag
sorry the ignorance again Jörg but I am getting this when using your method NoMethodError: undefined method `encode' for "hello":Stringhow can I use this encode correctly?
ludicco
@ludicco: It appears you are using an older version of Ruby. Multilingualization support has *massively* improved in Ruby 1.9. To be more precise: before Ruby 1.9, there *was no* m17n support, all m17n had to be handled explicitly by the programmer. In Ruby 1.8, you will have to use the `iconv` library from the standard library.
Jörg W Mittag
Ha! Thanks Jörg you're brilliant! And knows lots about programming, I'm amazed.
ludicco
Great answer. Highlights that the main reason that the two hashes by OP were different is the lack of conversion to UTF16-LE first, as `Unicode.GetBytes()` was doing. Also, bonus points for further explaining differences between Ruby 1.8/1.9, and providing a modern C# example of the original problem.
maxwellb