Search code examples
cryptographyurl-encodingrngcryptoserviceprovider

How to use RNGCryptoServiceProvider generated string in url/query string


NOTE: I have already solved the problem mentioned in this post. After doing lot of google I couldn't find right solution. As now I know the answer. I thought this post will save other developer's time trying to solve same.

Problem:

I wanted to Generate Cryptographic random string and send that as part of url to user. With Base64 string you will likely get Error:

The request filtering module is configured to deny a request that contains a double escape sequence

or it will not find your Route.

So either you hack/workaround and find/replace escape chars on Base64 String or use this solution.

This is how my original code look like.

  public string GenerateRandomString()
  {
     var randomBytes = GenerateRandomBytes(512);

     var randomString = Convert.ToBase64String(randomBytes);

     return randomString;
  }

  private byte[] GenerateRandomBytes(int keyBitLength)
  {
     using (var provider = new RNGCryptoServiceProvider())
     {
        var lengthInByte = keyBitLength / 8;
        var randomNumber = new byte[lengthInByte];
        provider.GetBytes(randomNumber);

        return randomNumber;
     }
  }

Solution is UrlTokenEncode. Added new method to convert random bytes to Url Encoded Token.

public string GenerateRandomStringToken()
{
    var randomBytes = GenerateRandomBytes(512);
    return HttpServerUtility.UrlTokenEncode(randomBytes);
}

private byte[] GenerateRandomBytes(int keyBitLength)
{
   using (var provider = new RNGCryptoServiceProvider())
   {
      var lengthInByte = keyBitLength / 8;
      var randomNumber = new byte[lengthInByte];
      provider.GetBytes(randomNumber);

      return randomNumber;
   }
}

Solution

  • In above question Solution is also provided.