-
Notifications
You must be signed in to change notification settings - Fork 38
/
env_crypto.go
80 lines (70 loc) · 1.51 KB
/
env_crypto.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
package command
import (
"crypto/aes"
"crypto/cipher"
cryptorand "crypto/rand"
"io"
"github.com/pkg/errors"
)
type EnvEncryptor struct {
source io.Reader
stream cipher.Stream
}
func NewEnvEncryptor(key []byte, nonce []byte, source io.Reader) (*EnvEncryptor, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.WithStack(err)
}
stream := cipher.NewCTR(block, nonce)
return &EnvEncryptor{
source: source,
stream: stream,
}, nil
}
func (e *EnvEncryptor) Read(p []byte) (n int, err error) {
n, readErr := e.source.Read(p)
if n > 0 {
e.stream.XORKeyStream(p[:n], p[:n])
return n, readErr
}
return 0, io.EOF
}
type EnvDecryptor struct {
source io.Reader
stream cipher.Stream
}
func NewEnvDecryptor(key []byte, nonce []byte, source io.Reader) (*EnvDecryptor, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.WithStack(err)
}
stream := cipher.NewCTR(block, nonce)
return &EnvDecryptor{
source: source,
stream: stream,
}, nil
}
func (d *EnvDecryptor) Read(p []byte) (n int, err error) {
n, readErr := d.source.Read(p)
if n > 0 {
d.stream.XORKeyStream(p[:n], p[:n])
return n, readErr
}
return 0, io.EOF
}
func createEnvEncryptionKey() ([]byte, error) {
key := make([]byte, 32)
_, err := cryptorand.Read(key)
if err != nil {
return nil, err
}
return key, nil
}
func createEnvEncryptionNonce() ([]byte, error) {
nonce := make([]byte, aes.BlockSize)
_, err := cryptorand.Read(nonce)
if err != nil {
return nil, err
}
return nonce, nil
}