krz/keycask

Password manager: Swift core library, CLI for macOS/Linux/Windows, iOS/macOS app. cli password-manager swift

Sources/KeycaskCore/Generator.swift

37 lines · 1318 bytes

 1public enum Generator {
 2    public static let alphabet: [Character] = Array(
 3        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{};:,.<>?"
 4    )
 5    public static let defaultLength = 24
 6    public static let wordSeparator = "-"
 7
 8    public static func password(length: Int) -> String {
 9        var rng = SystemRandomNumberGenerator()
10        return password(length: length, using: &rng)
11    }
12
13    public static func password(length: Int, using rng: inout some RandomNumberGenerator) -> String
14    {
15        var chars: [Character] = []
16        chars.reserveCapacity(max(length, 0))
17        for _ in 0..<max(length, 0) {
18            chars.append(alphabet[Int(rng.next(upperBound: UInt32(alphabet.count)))])
19        }
20        return String(chars)
21    }
22
23    public static func passphrase(words: Int) -> String {
24        var rng = SystemRandomNumberGenerator()
25        return passphrase(words: words, using: &rng)
26    }
27
28    public static func passphrase(words: Int, using rng: inout some RandomNumberGenerator) -> String
29    {
30        let list = Wordlist.words
31        var picked: [String] = []
32        for _ in 0..<max(words, 0) {
33            picked.append(list[Int(rng.next(upperBound: UInt32(list.count)))])
34        }
35        return picked.joined(separator: wordSeparator)
36    }
37}