Use limited length for password generation

This commit is contained in:
Danny Moesch 2020-03-07 22:40:45 +01:00 committed by Mingshen Sun
parent 15324af03c
commit 2c65173c71
2 changed files with 23 additions and 3 deletions

View file

@ -83,17 +83,17 @@ public struct PasswordGenerator: Codable {
private func generateRandom() -> String {
let currentCharacters = characters
if groups > 1, isAcceptable(groups: groups) {
return selectRandomly(count: length - groups + 1, from: currentCharacters)
return selectRandomly(count: limitedLength - groups + 1, from: currentCharacters)
.slices(count: UInt(groups))
.map { String($0) }
.joined(separator: "-")
}
return String(selectRandomly(count: length, from: currentCharacters))
return String(selectRandomly(count: limitedLength, from: currentCharacters))
}
private func generateXkcd() -> String {
let currentDelimiters = delimiters
return getRandomDelimiter(from: currentDelimiters) + (0 ..< length)
return getRandomDelimiter(from: currentDelimiters) + (0 ..< limitedLength)
.map { _ in getRandomWord() + getRandomDelimiter(from: currentDelimiters) }
.joined()
}

View file

@ -55,6 +55,26 @@ class PasswordGeneratorTest: XCTestCase {
XCTAssertFalse(generator.isAcceptable(groups: 4))
}
func testRandomGroupsCount() {
[
PasswordGenerator(length: 15, groups: 4),
PasswordGenerator(length: 24, groups: 5),
PasswordGenerator(length: 63, groups: 8),
].forEach { generator in
XCTAssertEqual(generator.generate().split(separator: "-").count, generator.groups)
}
}
func testXKCDWordsCount() {
[
PasswordGenerator(flavor: .xkcd, length: 4, useSpecialSymbols: false),
PasswordGenerator(flavor: .xkcd, length: 8, useSpecialSymbols: false),
PasswordGenerator(flavor: .xkcd, length: 1, useSpecialSymbols: false),
].forEach { generator in
XCTAssertEqual(generator.generate().split(whereSeparator: { "0123456789".contains($0) }).count, generator.limitedLength)
}
}
func testRandomPasswordLength() {
[
PasswordGenerator(),