Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hash to a hexadecimal character string

Tags:

string

c#

hex

hash

on this page:

http://www.shutterfly.com/documentation/OflyCallSignature.sfly

it says once you generate a hash you then:

convert the hash to a hexadecimal character string

is there code in csharp to do this?

like image 334
leora Avatar asked Sep 17 '09 01:09

leora


1 Answers

To get the hash, use the System.Security.Cryptography.SHA1Managed class.

EDIT: Like this:

byte[] hashBytes = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(str));

To convert the hash to a hex string, use the following code:

BitConverter.ToString(hashBytes).Replace("-", "");

If you want a faster implementation, use the following function:

private static char ToHexDigit(int i) {
    if (i < 10) 
        return (char)(i + '0');
    return (char)(i - 10 + 'A');
}
public static string ToHexString(byte[] bytes) {
    var chars = new char[bytes.Length * 2 + 2];

    chars[0] = '0';
    chars[1] = 'x';

    for (int i = 0; i < bytes.Length; i++) {
        chars[2 * i + 2] = ToHexDigit(bytes[i] / 16);
        chars[2 * i + 3] = ToHexDigit(bytes[i] % 16);
    }

    return new string(chars);
}
like image 67
SLaks Avatar answered Sep 28 '22 18:09

SLaks