-1
static public string GetRandomSalt(int saltLength)
    {
        byte[] saltByte = new byte[saltLength];

        using (var random = new RNGCryptoServiceProvider())
        {

            random.GetBytes(saltByte);
        }
        return Convert.ToBase64String(saltByte);
    }

so if the salt length is 8, it will returns some random string but ends with '=', how do I avoid it? looked at other stack overflow solution, but still cannot fix it

Lucas Chan
  • 87
  • 6
  • You *don't* fix it. You've created a base-64 encoded string, presumably to pass to something/someone else who will base-64 decode it (if not, why are you doing that conversion at all?). When they decode it, they *expect* the `=` to be there. – Damien_The_Unbeliever Aug 31 '18 at 14:38

3 Answers3

1

It's just Base64 padding you can't avoid, see here. See also Base64 specification.

I recommend using salt as byte array.

Community
  • 1
  • 1
Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
0

The problem is not related to the use of RNGCryptoServiceProvider, but rather that you are converting the result to base-64.

According to the documentation:

The valueless character "=" is used for trailing padding.

So, I can think of three options:

  1. Stop using base-64 formatting (possibly return the bytes themselves).
  2. Accept the fact that base-64 uses = for padding.
  3. Pass a length that doesn't require padding, like 9.

Example for point 3:

Convert.ToBase64String(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9})

produces

AQIDBAUGBwgJ
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
0
public static string GetUniqueKey(int maxSize)
{
    char[] chars = new char[62];
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
    byte[] data = new byte[1];
    using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
    {
        crypto.GetNonZeroBytes(data);
        data = new byte[maxSize];
        crypto.GetNonZeroBytes(data);
    }
    StringBuilder result = new StringBuilder(maxSize);
    foreach (byte b in data)
    {
        result.Append(chars[b % (chars.Length)]);
    }
    return result.ToString();
}
Taazar
  • 1,545
  • 18
  • 27