How to: Create a nonce in C#


SQL Steve

Creating a nonce

Within the realm of cryptography, a nonce is a random value used to thwart replay attacks.  In other words, if a man in the middle intercepts the first message and tries to send that message again, the receiver will be able to identify that it is a duplicate message and discard it as the nonce should be different for each message submission.

The code below generates a 20 byte nonce for use in the OAuth 1.0a protocol.

private static string CalculateNonce()
{
    //Allocate a buffer
    var ByteArray = new byte[20];
    //Generate a cryptographically random set of bytes
    using (var Rnd = RandomNumberGenerator.Create())
    {
        Rnd.GetBytes(ByteArray);
    }
    //Base64 encode and then return
    return Convert.ToBase64String(ByteArray);
}

View original post