Why do RNGCryptoServiceProvider values โ€‹โ€‹always end with equal signs?

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); } 

Each generated value:

i.e:.

 Qcr6OgNxkGzVebNl00Dtk7yCaz64owUx7pKEhl1Ogn4= IGFLQB0OrReDB3P6nuZgqZIkTwTtch9Fk3Rx/DL4CgI= UAJwLwIPYEJ9SzMAK/EMiUJ/DHhmfy6UVMM5MU6Dcpg= 

always ends with "=" - why is this?

I am sending this as a random string for the password reset, and I am having problems with Microsoft Outlook without raising = at the end of the link. Does anyone know about this without simply chopping up the last character of the string?

+4
source share
1 answer

This is due to the number of bytes returned. The = parameter is used as an add-on for base64.

EDIT

Using your algorithm, I generated strings using from 1 to 20 bytes, printing 1 result per line. As you can see, some lines end with the same characters, 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 No. 2

I realized that I explained why = happens, but never suggested another way to generate your URL parameter. One such method is the System.Web.HttpServerUtility.UrlTokenEncode () method, which converts an array of bytes into a user-friendly format. To convert a string back to an array of bytes, use the System.Web.HttpServerUtility.UrlTokenDecode () method.

+10
source

Source: https://habr.com/ru/post/1394656/


All Articles