Question

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?

Was it helpful?

Solution

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);
}

OTHER TIPS

I can't comment yet, not enough rep, but Lior is mixing Java with C# in a very wrong answer.

byte in C# is an unsigned byte, which is the complete opposite of all other whole number types in C#, which are signed by default.

The 0xFF part is completely pointless because even if byte was signed, 0xFE for example is -2. Using a bitwise-and with 0xFE and 0xFF, for example, would not stop negative number 0xFE from being the outcome. 0x7F would.

Regarding the top answer, I'm pretty sure these micro-optimizations might help, albeit, they're micro-optimizations that are likely to not make any real difference because the JIT compiler might just do something else and because computers are just too blazing fast.

    chars[2 * i + 2] = ToHexDigit(bytes[i] / 16);
    chars[2 * i + 3] = ToHexDigit(bytes[i] % 16);

Small change to make it use bitshift and bitwise ops instead of the divider and modulo.

    chars[2 * i + 2] = ToHexDigit((bytes[i] >> 4) & 0xF);
    chars[2 * i + 3] = ToHexDigit(bytes[i] & 0xF);

This is the other "optimization", although I see it as a more readable thing. Maybe that's because I know most of the ASCII table by heart.

    private static char ToHexDigit(int i)
    {
        return (char)(i + (i < 10 ? 48 : 55));
    }

If you're trying to achieve lower case hex (without ToLower), just swap 55 with 87. It makes it quite simple.

Update: It looks like Lior or someone removed his very off answer. That was a good move.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top