-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt.go
104 lines (84 loc) · 2.17 KB
/
crypt.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
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"io"
"os"
)
var (
// ErrCipherTextTooShort is thrown when cipher text is too short
ErrCipherTextTooShort = errors.New("utils/credentials: ciphertext too short")
// ... random bytes
iv = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05}
)
// Encrypt will encrypt the plain text using the passphrase passed as a parameter
func Encrypt(plaintext, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Ciphertext FeedBack
cfb := cipher.NewCFBEncrypter(block, iv)
ciphertext := make([]byte, len(plaintext))
cfb.XORKeyStream(ciphertext, plaintext)
return Encode(ciphertext), nil
}
// Encode will encode a buffer with base64
func Encode(b []byte) []byte {
return []byte(base64.StdEncoding.EncodeToString(b))
}
// Decrypt will decrypt the cipher text using the passphrase passed as a parameter
func Decrypt(ciphertext, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext, err = Decode(ciphertext)
if err != nil {
return nil, err
}
cfb := cipher.NewCFBDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
cfb.XORKeyStream(plaintext, ciphertext)
return plaintext, nil
}
// Decode will decode a buffer with base64
func Decode(b []byte) ([]byte, error) {
return base64.StdEncoding.DecodeString(string(b))
}
// ReadOnlyFilePassphrase will read the passphrase from a file
func ReadOnlyFilePassphrase(filename string) (string, error) {
var (
f *os.File
err error
)
if f, err = os.OpenFile(filename, os.O_RDONLY, 0400); err != nil {
return "", err
}
b, err := io.ReadAll(f)
if err != nil {
return "", err
}
b, err = Decode(b)
if err != nil {
return "", err
}
if len(b) != 32 {
return "", ErrCipherTextTooShort
}
return string(b), nil
}
// WritePassphraseToFile will write the passphrase to the file
func WritePassphraseToFile(filename string, passphrase []byte) error {
var (
f *os.File
err error
)
if f, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0664); err != nil {
return err
}
_, err = f.Write(passphrase)
return err
}