-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.go
441 lines (410 loc) · 10.9 KB
/
functions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package krypto431
import (
"errors"
"math"
"os"
"strings"
"unicode"
"github.com/sa6mwa/krypto431/crand"
"golang.org/x/crypto/ssh/terminal"
)
// Functions not assigned to methods of more general use likely end up here.
func TrimRightRuneFunc(s []rune, f func(rune) bool) []rune {
for i := len(s); i > 0; i-- {
if f(s[i-1]) {
s = s[:i-1]
} else {
break
}
}
return s
}
// Configure go-password-validator minimum entropy for the entire krypto431
// package. Entropy limit is not instance-scoped (yet).
func SetMinimumPasswordEntropyBits(entropy float64) {
MinimumPasswordEntropyBits = entropy
}
// RandomAlnumRunes generates a case-sensitive alpha-numeric string as a rune
// slice of the length n. Returns a rune slice.
func RandomAlnumRunes(n int) []rune {
id := make([]rune, n)
for i := range id {
//num := crand.Intn(26 + 26)
num := crand.Intn(26 + 26 + 10) // Max return number is n-1
switch {
case num < 26:
id[i] = rune(num) + rune('A')
case num >= 26 && num < 52:
id[i] = rune(num) - 26 + rune('a')
case num >= 52:
id[i] = rune(num) - 52 + rune('0')
}
}
return id
}
// IsTerminal returns true if os.Stdin is a terminal, false if not.
func IsTerminal() bool {
return terminal.IsTerminal(int(os.Stdin.Fd()))
}
// Returns a rune slice where each group is separated by a space. If columns is
// above 0 the function will insert a line break instead of a space before
// extending beyond that column length. Don't forget to Wipe(myRuneSlice) when
// you are done!
func groups(input *[]rune, groupsize int, columns int) (*[]rune, error) {
if input == nil {
return nil, ErrNilPointer
}
if groupsize <= 0 {
return nil, errors.New("groupsize must be above 0")
}
output := make([]rune, 0, int(math.Ceil(float64(len(*input))/float64(groupsize)))*(groupsize+1))
runeCount := 0
outCount := 0
for i := 0; i < len(*input); i++ {
output = append(output, (*input)[i])
outCount++
runeCount++
if runeCount == groupsize {
if i != len(*input)-1 {
if columns > 0 && outCount >= columns-groupsize-1 {
output = append(output, []rune(LineBreak)...)
outCount = 0
} else {
output = append(output, rune(' '))
outCount++
}
}
runeCount = 0
}
}
return &output, nil
}
// AllNeedlesInHaystack returns true is all needles can be found in the
// haystack. Final variadic is optional, first true will match case-insensitive
// instead of matching case. Intended to find Keepers of Keys where needles are
// Message.Recipients and haystack is Key.Keepers.
func AllNeedlesInHaystack(needles *[][]rune, haystack *[][]rune, caseInsensitive ...bool) bool {
if needles == nil || haystack == nil {
return false
}
if len(*needles) == 0 || len(*haystack) == 0 {
return false
}
loop:
for i := range *needles {
for x := range *haystack {
if len(caseInsensitive) > 0 && caseInsensitive[0] {
if EqualRunesFold(&(*haystack)[x], &(*needles)[i]) {
continue loop
}
} else {
if EqualRunes(&(*haystack)[x], &(*needles)[i]) {
continue loop
}
}
}
return false
}
return true
}
func AnyNeedleInHaystack(needles *[][]rune, haystack *[][]rune) bool {
if needles == nil || haystack == nil {
return false
}
if len(*needles) == 0 || len(*haystack) == 0 { // do not need len(*needles), but be explicit
return false
}
for i := range *needles {
for x := range *haystack {
if EqualRunes(&(*haystack)[x], &(*needles)[i]) {
return true
}
}
}
return false
}
func AnyOfThem(haystack *[][]rune, needle *[]rune) bool {
if haystack == nil || needle == nil {
return false
}
if len(*needle) == 0 {
return false
}
for i := range *haystack {
if EqualRunes(&(*haystack)[i], needle) {
return true
}
}
return false
}
// Generic function to convert an array of rune slices (runes) into a string
// slice.
func RunesToStrings(runes *[][]rune) (stringSlice []string) {
for i := range *runes {
stringSlice = append(stringSlice, string((*runes)[i]))
}
return
}
// Wrapper to strings.Join for a pointer to slices of rune slices. Returns a
// string with 'separator' as delimiter between items.
func JoinRunesToString(runes *[][]rune, separator string) string {
return strings.Join(RunesToStrings(runes), separator)
}
// Generic function to vet one or more keeper strings, comma/space-separated or
// not. Returns a slice of rune slices with the keepers for use in e.g
// Key.Keepers.
func VettedKeepers(keepers ...string) (vettedKeepers [][]rune) {
f := func(c rune) bool {
return c == ',' || c == ' '
}
for i := range keepers {
subKeepers := strings.FieldsFunc(keepers[i], f)
for a := range subKeepers {
vettedKeeper := []rune(strings.ToUpper(strings.TrimSpace(subKeepers[a])))
if len(vettedKeeper) > 0 {
vettedKeepers = append(vettedKeepers, vettedKeeper)
}
}
}
return
}
// VettedRecipients is an alias for VettedKeepers.
func VettedRecipients(recipients ...string) [][]rune {
return VettedKeepers(recipients...)
}
// VettedCallSigns is an alias for VettedKeepers.
func VettedCallSigns(callsigns ...string) [][]rune {
return VettedKeepers(callsigns...)
}
// VettedKeys is an alias for VettedKeepers.
func VettedKeys(keys ...string) [][]rune {
return VettedKeepers(keys...)
}
// VettedMessageIds is NOT an alias for VettedKeepers :). Returns a slice of
// rune slices where case is preserved from the input (message IDs are
// case-sensitive). As with keepers, IDs can be space or comma separated.
func VettedMessageIds(ids ...string) [][]rune {
var vettedMessageIds [][]rune
f := func(c rune) bool {
return c == ',' || c == ' '
}
for i := range ids {
subIds := strings.FieldsFunc(ids[i], f)
for a := range subIds {
vettedMessageId := []rune(strings.TrimSpace(subIds[a]))
if len(vettedMessageId) > 0 {
vettedMessageIds = append(vettedMessageIds, vettedMessageId)
}
}
}
return vettedMessageIds
}
// Compare two rune slices. Returns true if they are equal, false if
// not.
func EqualRunes(a *[]rune, b *[]rune) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if len(*a) != len(*b) {
return false
}
for x := range *a {
if (*a)[x] != (*b)[x] {
return false
}
}
return true
}
// Same as EqualRunes, except EqualRunesFold is case-insensitive. Returns true
// if they are equal fold, false if not.
func EqualRunesFold(a *[]rune, b *[]rune) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if len(*a) != len(*b) {
return false
}
for x := range *a {
if unicode.ToUpper((*a)[x]) != unicode.ToUpper((*b)[x]) {
return false
}
}
return true
}
// ColumnSizes calculates max length of each []rune in a slice of []rune slices.
// If optional column headers are provided (as a string slice), their length
// will be taken into account as well. Left for legacy, replaced by
// predictColumnSizes().
func ColumnSizes(rs [][][]rune, headerFields ...string) (columnSizes []int) {
for item := range rs {
for col := range rs[item] {
ilen := len(rs[item][col])
if len(headerFields) >= col {
hlen := len(headerFields[col])
if hlen > ilen {
ilen = hlen
}
}
if len(columnSizes) <= col {
columnSizes = append(columnSizes, ilen)
} else {
if columnSizes[col] < ilen {
columnSizes[col] = ilen
}
}
}
}
return
}
// Function internal to SummaryOfKeys(), faster than previous method (digest and
// ColumnSizes). Assumes the following header:
//
// []string{"ID", "KEEPERS", "CREATED", "EXPIRES", "USED", "COMPROMISED", "COMMENT"}
func predictColumnSizesOfKeys(keys []*Key) (columnSizes [7]int) {
if len(keys) > 0 {
if keys[0] == nil {
return
}
// Just assume key length is the instance's group size of the first key in
// the slice.
columnSizes[0] = keys[0].instance.GroupSize
// Keepers header is the initial length of the keepers column
columnSizes[1] = len("KEEPERS")
// Created and Expires are fixed length
columnSizes[2] = len("012345ZJAN23")
columnSizes[3] = len("012345ZJAN23")
// Used and Compromised are normally the length of their headers
columnSizes[4] = HighestInt(len(Words["No"]), len(Words["Yes"]), len("USED"))
columnSizes[5] = HighestInt(len(Words["No"]), len(Words["Yes"]), len("COMPROMISED"))
for i := range keys {
if keys[i] == nil {
continue
}
var keepersLength int
if len(keys[i].Keepers) == 0 {
keepersLength = len("Anonymous")
if columnSizes[1] < keepersLength {
columnSizes[1] = keepersLength
}
} else {
for x := range keys[i].Keepers {
keepersLength += len(keys[i].Keepers[x]) + 1
}
if keepersLength > 0 && columnSizes[1] < keepersLength {
columnSizes[1] = keepersLength - 1
}
}
clen := len(keys[i].Comment)
if columnSizes[6] < clen {
columnSizes[6] = clen
}
}
}
return
}
func predictColumnSizesOfMessages(messages []*Message) (columnSizes [5]int) {
if len(messages) > 0 {
if messages[0] == nil {
return
}
}
// MessageId is pretty hard-coded
columnSizes[0] = 4
// DTG is fixed
columnSizes[1] = len("012345ZJAN23")
columnSizes[2] = len("TO")
columnSizes[3] = len("DE")
columnSizes[4] = 35 //len("DIGEST")
for i := range messages {
if messages[i] == nil {
continue
}
var recipientsLength int
if len(messages[i].Recipients) == 0 {
recipientsLength = len(NilRunes)
if columnSizes[2] < recipientsLength {
columnSizes[2] = recipientsLength
}
} else {
for x := range messages[i].Recipients {
recipientsLength += len(messages[i].Recipients[x]) + 1
}
if recipientsLength > 0 && columnSizes[2] < recipientsLength {
columnSizes[2] = recipientsLength - 1
}
}
fromLen := len(messages[i].From)
if columnSizes[3] < fromLen {
columnSizes[3] = fromLen
}
}
return
}
func padding(s []rune, fieldLength int) (spaces []rune) {
padCount := fieldLength - len(s)
for x := 0; x < padCount; x++ {
spaces = append(spaces, rune(' '))
}
return
}
func withPadding(s []rune, fieldLength int) []rune {
return append(s, padding(s, fieldLength)...)
}
// Maximum int in int slice. Alternative MaxInt function.
func HighestInt(number ...int) (highest int) {
if len(number) == 0 {
return 0
}
//highest = -int(^uint(0)>>1) - 1
highest = math.MinInt
for _, n := range number {
if n > highest {
highest = n
}
}
return
}
// Minimum int in int slice. Alternative MinInt function.
func LowestInt(number ...int) (lowest int) {
if len(number) == 0 {
return 0
}
//lowest = int(^uint(0) >> 1)
lowest = math.MaxInt
for _, n := range number {
if n < lowest {
lowest = n
}
}
return
}
// Returns a copy of a rune slice.
func RuneCopy(src *[]rune) []rune {
if src == nil {
return []rune{}
}
runeCopy := make([]rune, len(*src))
copy(runeCopy, *src)
return runeCopy
}
func RunePtr(s []rune) *[]rune {
return &s
}
// Returns a copy of a byte slice.
func ByteCopy(src *[]byte) []byte {
if src == nil {
return []byte{}
}
byteCopy := make([]byte, len(*src))
copy(byteCopy, *src)
return byteCopy
}
func BytePtr(s []byte) *[]byte {
return &s
}