Password Generator with Dart

Password Generator with Dart

ยท

0 min read

Hi everyone as my side project I wrote an Android App to generate strong password for my online accounts and I made it with Flutter. This is the Dart code that makes all happen:

import 'dart:math';

/**
 * @desc Function to generate password based on some criteria
 * @param bool _isWithLetters: password must contain letters
 * @param bool _isWithUppercase: password must contain uppercase letters
 * @param bool _isWithNumbers: password must contain numbers
 * @param bool _isWithSpecial: password must contain special chars
 * @param int _numberCharPassword: password length
 * @return string: new password
 */
String generatePassword(bool _isWithLetters, bool _isWithUppercase,
    bool _isWithNumbers, bool _isWithSpecial, double _numberCharPassword) {

  //Define the allowed chars to use in the password
  String _lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
  String _upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  String _numbers = "0123456789";
  String _special = "@#=+!ยฃ\$%&?[](){}";

  //Create the empty string that will contain the allowed chars
  String _allowedChars = "";

  //Put chars on the allowed ones based on the input values
  _allowedChars += (_isWithLetters ? _lowerCaseLetters : '');
  _allowedChars += (_isWithUppercase ? _upperCaseLetters : '');
  _allowedChars += (_isWithNumbers ? _numbers : '');
  _allowedChars += (_isWithSpecial ? _special : '');

  int i = 0;
  String _result = "";

  //Create password
  while (i < _numberCharPassword.round()) {
    //Get random int
    int randomInt = Random.secure().nextInt(_allowedChars.length);
    //Get random char and append it to the password
    _result += _allowedChars[randomInt];
    i++;
  }

  return _result;
}

How to use

All you have to do is to create a dart file with the code above, name it password_generator.dart, import it in your statefull or stateless widget and directly call the generatePassword() function

import 'password_generator.dart';

//Create a password with letters, uppercase letters, numbers but not special chars with 17 chars
String _generatedPassword = generatePassword(true, true, true, false, 17);
print(_generatedPassword);  //It's prints for example: 87nj4KUlN00GjdxoD

The app is ready to download on the Play Store using this link: Wassword - Wonderful Password Generator.

Code strong, Alberto