0

I am trying to generate a string or password. where the user defines minimum numbers or special characters. if the minimum number is 3 then generated string should have 3 numbers

here is the code i used to generate string

String generaterandomPassword() {
        final length = _length.toInt();
        const letterLowerCase = "abcdefghijklmnopqrstuvwxyz";
        const letterUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const number = '0123456789';
        const special = '@#%^*>\$@?/[]=+';
    
        String chars = "";
        // if (letter) chars += '$letterLowerCase$letterUpperCase';
        if (_uppercaseatoz) chars += letterUpperCase;
        if (_lowercaseatoz) chars += letterLowerCase;
        if (_number) chars += number;
        if (_specialchar) chars += special;
    
        return List.generate(
          length,
          (index) {
            final indexRandom = Random.secure().nextInt(chars.length);
            return chars[indexRandom];
          },
        ).join('');
      }
1
  • What is wrong with what you've presented? Commented Nov 4, 2022 at 20:35

1 Answer 1

5

One way to guarantee a minimum number of "special" characters is:

  1. Generate a string with that minimum length that consists of only special characters.
  2. Randomly choose any characters for the remainder.
  3. Shuffle all of the generated characters.

For example:

import 'dart:math';

final random = Random.secure();

const letterLowerCase = "abcdefghijklmnopqrstuvwxyz";
const letterUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const number = '0123456789';
const special = '@#%^*>\$@?/[]=+';

String generatePassword({
  required int length,
  required int minimumSpecialCharacterCount,
}) {
  assert(length >= minimumSpecialCharacterCount);
  
  const allValidCharacters = '$letterLowerCase$letterUpperCase$number$special';

  var specials = [
    for (var i = 0; i < minimumSpecialCharacterCount; i += 1)
      special[random.nextInt(special.length)],
  ];

  var rest = [
    for (var i = 0; i < length - minimumSpecialCharacterCount; i += 1)
      allValidCharacters[random.nextInt(allValidCharacters.length)],
  ];

  return ((specials + rest)..shuffle(random)).join();
}

void main() {
  print(generatePassword(length: 16, minimumSpecialCharacterCount: 3));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.