forked from 1Password/shell-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_secrets.go
102 lines (79 loc) · 1.91 KB
/
example_secrets.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
package plugintest
import (
"fmt"
"log"
"math/rand"
"strings"
"time"
"github.com/1Password/shell-plugins/sdk/schema"
)
const (
lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"
capitalCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:`"
secretExampleSuffix = "EXAMPLE"
)
var seededRand = rand.New(
rand.NewSource(time.Now().UnixNano()))
func ExampleSecretFromComposition(v schema.ValueComposition) string {
prefix := getPrefix(v)
suffix := getSuffix(v)
base := generateBase(v, v.Length-len(prefix)-len(suffix))
return prefix + base + suffix
}
func getPrefix(v schema.ValueComposition) string {
if v.Prefix != "" {
return v.Prefix
}
return ""
}
func generateBase(v schema.ValueComposition, baseLength int) string {
chars := charsToUse(v.Charset)
generatedStr, err := stringFromCharset(baseLength, chars)
if err != nil {
log.Fatalf("Error while generating secret: %v", err)
}
return generatedStr
}
func getSuffix(v schema.ValueComposition) string {
var suffix string
if v.Length > len(secretExampleSuffix) && (v.Charset.Uppercase || v.Charset.Lowercase) {
suffix = secretExampleSuffix
if v.Charset.Lowercase && !v.Charset.Uppercase {
suffix = strings.ToLower(secretExampleSuffix)
}
}
return suffix
}
func stringFromCharset(length int, charset string) (string, error) {
if charset == "" {
return "", fmt.Errorf("invalid charset provided")
}
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b), nil
}
func charsToUse(c schema.Charset) string {
var chars string
if c.Uppercase {
chars += capitalCaseLetters
}
if c.Lowercase {
chars += lowerCaseLetters
}
if c.Digits {
chars += digits
}
if c.Symbols {
chars += symbols
}
if len(c.Specific) > 0 {
for _, r := range c.Specific {
chars += string(r)
}
}
return chars
}