Search code examples
c#stringspecial-charactersbackslashpassword-generator

PasswordGenerator package is generating unwanted special char


I'm using the PasswordGenerator(2.05) package in order to generate password.

One of the methods allows me to choose which special characters I can include.

Here is my code:

public static string GetUniquePassword(
        int i_lengthOfPassword = 8,
        bool i_includeLowercase = true, 
        bool i_includeUppercase = true, 
        bool i_includeNumeric = true,
        bool i_includeSpecial = true)
    {
        var pwd = new Password(includeLowercase: i_includeLowercase,
                               includeUppercase: i_includeUppercase,
                               includeNumeric: i_includeNumeric,
                               includeSpecial: i_includeSpecial,
                               passwordLength: i_lengthOfPassword).IncludeSpecial("!@#$%^&*,");

        string passwordResult = pwd.Next();
        return passwordResult;
    }

The actual result is that once in a while I'm getting a password that includes the special character \ which my app doesn't allow.

For instance : 2\8$Y!f0.

I'll be happy if the generator won't include this character.

Is there any workaround?


Solution

  • If I'm not reading the code incorrectly, you actually want this:

    IPassword pwd = new Password(includeLowercase: i_includeLowercase,
                           includeUppercase: i_includeUppercase,
                           includeNumeric: i_includeNumeric,
                           includeSpecial: false,
                           passwordLength: i_lengthOfPassword);
    
    if (i_includeSpecial)
    {
        pwd = pwd.IncludeSpecial("!@#$%^&*,");
    }
    

    You need to set includeSpecial to false in the Password constructor, otherwise the constructor of PasswordSettings (which it calls) will have already added all the usual special characters.

    .NET Fiddle