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.
Ng==
HAo=
g+h1
pdR+cQ==
z5bFWwc=
BilTQWCU
kXo96Jilxw==
7jc16UHgbGc=
DnLzoSDUNVfQ
6MwGWLD3ZcbfZA==
hADhg4HFdMVi1n0=
cWm2HEKs48VaoYgl
TrwxX20FmEs7o8u2ag==
WLORuUzewYDB18XFAcc=
tSnvFVVm/NZ2tkXJnB6V
McUWf0mAmM5/0Upu+eYd+w==
Eln3QPMr2VjXt4e3GsZuOXo=
DBYLTG3fDbMC5I1bnYmG/NxH
KgGhxdZjmjUypsqnbQUMCJzVrQ==
yI+3sFdzBX4Xfb2u6xuzQdS9II0=
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With