-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
secret_unprotected.go
94 lines (72 loc) · 1.87 KB
/
secret_unprotected.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
package config
import (
"bytes"
"unsafe"
)
type unprotectedSecretImpl struct{}
func (*unprotectedSecretImpl) Container(secret []byte) secretContainer {
return &unprotectedSecretContainer{buf: newUnlockedBuffer(secret)}
}
func (*unprotectedSecretImpl) EmptyBuffer() SecretBuffer {
return &unlockedBuffer{}
}
func (*unprotectedSecretImpl) Wipe(secret []byte) {
for i := range secret {
secret[i] = 0
}
}
type unlockedBuffer struct {
content []byte
}
func newUnlockedBuffer(secret []byte) *unlockedBuffer {
return &unlockedBuffer{bytes.Clone(secret)}
}
func (lb *unlockedBuffer) Size() int {
return len(lb.content)
}
func (lb *unlockedBuffer) Grow(_ int) {
// The underlying byte-buffer will grow dynamically
}
func (lb *unlockedBuffer) Bytes() []byte {
return lb.content
}
func (lb *unlockedBuffer) TemporaryString() string {
//nolint:gosec // G103: Valid use of unsafe call to cast underlying bytes to string
return unsafe.String(&lb.content[0], len(lb.content))
}
func (lb *unlockedBuffer) String() string {
return string(lb.content)
}
func (lb *unlockedBuffer) Destroy() {
selectedImpl.Wipe(lb.content)
lb.content = nil
}
type unprotectedSecretContainer struct {
buf *unlockedBuffer
}
func (c *unprotectedSecretContainer) Destroy() {
if c.buf == nil {
return
}
// Wipe the secret from memory
c.buf.Destroy()
c.buf = nil
}
func (c *unprotectedSecretContainer) Equals(ref []byte) (bool, error) {
if c.buf == nil {
return false, nil
}
return bytes.Equal(c.buf.content, ref), nil
}
func (c *unprotectedSecretContainer) Buffer() (SecretBuffer, error) {
if c.buf == nil {
return &unlockedBuffer{}, nil
}
return newUnlockedBuffer(c.buf.content), nil
}
func (c *unprotectedSecretContainer) AsBuffer(secret []byte) SecretBuffer {
return &unlockedBuffer{secret}
}
func (c *unprotectedSecretContainer) Replace(secret []byte) {
c.buf = newUnlockedBuffer(secret)
}