I never tried to generate passwords myself but in this day of big companies getting hacked all the time, i feel it's safer to impose (generate and not let change except getting a newly generated for reset). The reasoning is that since users tend to reuse passwords, you getting hacked means they're unsafe on other websites, but other websites getting hacked also means their accounts can be compromised on mine.
So i tried my hand at this but i know this is a complex subject and most everytime someone asks about it they get a lot of stuff wrong, i wanted to check if i missed anything obvious that breaks the password strenght.
string GeneratePassword (int length)
{
var bytes = new byte[length];
// Don't store and reuse a generator to avoid predictable sequences.
var generator = System.Security.Cryptography.RNGCryptoServiceProvider.Create();
generator.GetBytes(bytes);
var chars = new char[]
{
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'0','1','2','3','4','5','6','7','8','9','!','.'
};
return new string(bytes
.Select(b=>chars[b%64])
.ToArray());
}
I picked a 64 set of chars to map to as it's a divisor of 256 (so no char will repeat more often) and it seemed like a decent balance between security and pushing ugly characters on the user.
Any advice is most welcome but my question is "is this a secure / safe way to generate passwords or am i missing some form of pattern / weakness that could make this exploitable?"