Here is my method:
public static string GenerateRandomString(int bytes)
{
var rng = new RNGCryptoServiceProvider();
var randomBytes = new byte[bytes];
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
}
Every value generated:
i.e.:
Qcr6OgNxkGzVebNl00Dtk7yCaz64owUx7pKEhl1Ogn4=
IGFLQB0OrReDB3P6nuZgqZIkTwTtch9Fk3Rx/DL4CgI=
UAJwLwIPYEJ9SzMAK/EMiUJ/DHhmfy6UVMM5MU6Dcpg=
always ends with “=” – why is this?
I’m sending this as a random string for a password reset email and am having issues with Microsoft Outlook not picking up the = at the end of the link. Is anyone aware of a way around this without simply chopping off the last character of the string?
It has to do with the number of bytes returned. The = is used as padding for base64.
EDIT
Using your algorithm I generated strings using between 1 and 20 bytes, printing 1 result per line. As you can see, some strings end with equal signs, others do not.
EDIT #2
I realized that I explained why the = occurs, but never suggested another way to generate your URL parameter. One such way is the System.Web.HttpServerUtility.UrlTokenEncode() method which converts an array of bytes to an url-friendly format. To convert the string back to an array of bytes, use the System.Web.HttpServerUtility.UrlTokenDecode() method.