HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Generating (presumably) unique `nonce` fields for Twitter OAuth

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uniqueoauthnoncefieldsgeneratingfortwitterpresumably

Problem

This is code that's part of a library (closed source) that I have that generates a unique nonce value for Twitter OAuth. Essentially, it generates a random number, combines it in string form with an extra string separated by a pipe, computes a Sha-1 hash, and then repeats the process if the Sha-1 hash (when converted to Base64) contained any non-alpha-numeric characters, which are subsequently stripped.

/// 
/// Generates a (presumably) unique NONCE string for use in Twitter OAuth requests.
/// 
/// Extra data to add during generation.
/// 
/// A (presumably) unique NONCE string.
/// 
/// 
/// While we can assume the generated NONCE strings will be somewhat unique, there is a small possibility that they will not be, and in such cases a new NONCE should be generated.
/// 
/// The generated NONCE values are 32 characters in length, and are generated by a Sha-1 hash and a Random generator, which generates four random numbers to be hashed until the generated string is 32 characters in length.
/// 
public string GenerateNonce(string extra = "")
{
    string result = "";
    SHA1 sha1 = SHA1.Create();

    Random rand = new Random();

    while (result.Length < 32)
    {
        string[] generatedRandoms = new string[4];

        for (int i = 0; i < 4; i++)
        {
            generatedRandoms[i] = rand.Next().ToString();
        }

        result += Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(string.Join("", generatedRandoms) + "|" + extra))).Replace("=", "").Replace("/", "").Replace("+", "");
    }

    return result.Substring(0, 32);
}


The idea is to generate somewhat unique nonce strings for use with Twitter OAuth (et al.).

I use the term "presumably," because, while it's not considered a bug that the nonce strings will not be guaranteed to be unique, collisions are expected to be fairly rare. I do welcome any and all suggestions that would lead to more uniqueness.

Solution

If I understand the requirements correctly, Guid.NewGuid().ToString("N") would work for generating a nonce.


A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

The "N" format specifier will return the GUID as 32 (lowercase) hexadecimal digits.

Context

StackExchange Code Review Q#106870, answer score: 22

Revisions (0)

No revisions yet.