ardawan.com

Password Maker



update June 21, 2017

Live: github.com/ardawan/PasswordMaker

A simple Password Maker to generate different strength level and lengths passwords in Swift.

I code this in swift 3 only for practice purpose. Of course, this is not the best password maker but the source code is available on Github.


feature

This password maker is generating characters in alpha, alphaNumeric and all characters in a specific quantity.

I was planning to have a function which gets strength level and length to generate the new password. to do so I needed to use a Switch statement in the main function generatePassword(strength type:Int, length:Int) to detect the strength level.  The levels 1 to 3 means low to high strength. simply the first case meaning only use alpha -(A…Z, a…z), second case alphaNumeric -(A…Z,a…z,0…9) and the last case all possible characters -(A…Z,a…z,0…9,!@#$~%^&*()_+=-:”;’./,{}[])

The Algorithm is like

  • Get strength level, length
  • Generate random chars based on the strength level. -Alpha, AlphaNumeric, SpecialChars
  • Shuffle the result
  • Print the New Password
password maker result

Password maker result

 


challenge

The entire code is based on random values so I’m going to get random value many times. it’s better to have a function to just pass my range and get the random value.

I made my first function, random(). The random(_ number:Int) -> Int will get an integer as the parameter and return an integer between 0 to the parameter value. super easy.

func random(_ number:Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

I made my own version of shuffle function to shuffle the final result. was a bit challenging to make the shuffle function for the first time. I named it shuffle(_ chars:[String]) -> String . The shuffle() will collect the chosen character as an array and shuffle it.

func shuffle(_ chars:[String]) -> String {
   var str = chars
    for q in 0..<chars.count {
    let x = random(chars.count)
    let value = str[x]
    str[x] = str[q]
    str[q] = value
    }
return str.joined()
}

To generate characters i put all the characters in an array. To get the result i called random function in a loop to get characters from array’s index and then append the value.

func randomNumeric(len:Int) -> [String] {
    let numeric = [1,2,3,4,5,6,7,8,9,0]
    var result:[String] = []
    for _ in 0..<len { result.append(String(numeric[random(numeric.count)])) }
    return result
}

The other patterns such as Alpha and Special Chars will follow the same approch. The full code is on Github


access

You can get the source code on my Github. Don’t forget to share your feedback with me on @ardawanizadi.