comparison src/main/kotlin/name/blackcap/passman/Generate.kt @ 0:a6cfdffcaa94

Initial commit, incomplete but it runs sorta.
author David Barts <n5jrn@me.com>
date Sun, 11 Sep 2022 16:11:37 -0700
parents
children 698c4a3d758d
comparison
equal deleted inserted replaced
-1:000000000000 0:a6cfdffcaa94
1 package name.blackcap.passman
2
3 import java.lang.IllegalArgumentException
4 import java.security.SecureRandom
5 import java.util.Random
6
7 /* ASCII, alphanumeric, no 0's, 1's, I's, O's or l's to avoid confusion. */
8 private const val DIGITS = "23456789"
9 private const val UPPERS = "ABCDEFGHJKLMNPQRSTUVWXYZ"
10 private const val LOWERS = "abcdefghijkmnopqrstuvwxyz"
11 /* \ can confuse *NIX, |, ', and ` invite confusion */
12 private const val SYMBOLS = "!\"#$%&()*+,-./:;<=>?@[]^_{}~"
13 const val MIN_GENERATED_LENGTH = 6
14 const val DEFAULT_GENERATED_LENGTH = 12
15
16 fun generate(length: Int, allowSymbols: Boolean): CharArray {
17 /* insecure, and if REALLY short, causes bugs */
18 if (length < MIN_GENERATED_LENGTH) {
19 throw IllegalArgumentException("length of $length is less than $MIN_GENERATED_LENGTH")
20 }
21
22 /* determine allowed characters */
23 val passchars = if (allowSymbols) {
24 DIGITS + UPPERS + LOWERS + SYMBOLS
25 } else {
26 DIGITS + UPPERS + LOWERS
27 }
28
29 /* ensure we get one of each class of characters */
30 val randomizer = SecureRandom()
31 val generated = CharArray(length)
32 generated[0] = randomized(DIGITS, randomizer)
33 generated[1] = randomized(UPPERS, randomizer)
34 generated[2] = randomized(LOWERS, randomizer)
35 var i = 3
36 if (allowSymbols) {
37 generated[3] = randomized(SYMBOLS, randomizer)
38 i = 4
39 }
40
41 /* generate the rest of the characters */
42 while (i < length) {
43 generated[i++] = randomized(passchars, randomizer)
44 }
45
46 /* scramble them */
47 for (i in 0 until length) {
48 val j = randomizer.nextInt(length)
49 if (i != j) {
50 val temp = generated[i]
51 generated[i] = generated[j]
52 generated[j] = temp
53 }
54 }
55
56 /* AMF... */
57 return generated
58 }
59
60 private fun randomized(passchars: String, randomizer: Random): Char =
61 passchars[randomizer.nextInt(passchars.length)]