Generating (presumably) unique `nonce` fields for Twitter OAuth 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.

/// &lt;summary&gt;
/// Generates a (presumably) unique NONCE string for use in Twitter OAuth requests.
/// &lt;/summary&gt;
/// &lt;param name="extra"&gt;Extra data to add during generation.&lt;/param&gt;
/// &lt;returns&gt;
/// A (presumably) unique NONCE string.
/// &lt;/returns&gt;
/// &lt;remarks&gt;
/// 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.
/// &lt;/remarks&gt;
public string GenerateNonce(string extra = "")
{
    string result = "";
    SHA1 sha1 = SHA1.Create();

    Random rand = new Random();

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

        for (int i = 0; i &lt; 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.
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.