-
Notifications
You must be signed in to change notification settings - Fork 13
/
crypt.go
56 lines (44 loc) · 1.13 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
package vault
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
func encrypt(data []byte, salt []byte, key *key) ([]byte, error) {
aesCipher, err := aes.NewCipher(key.cipherKey)
if err != nil {
return nil, err
}
plaintext := pad(data)
ciphertext := make([]byte, len(plaintext))
aesBlock := cipher.NewCTR(aesCipher, key.iv)
aesBlock.XORKeyStream(ciphertext, plaintext)
return ciphertext, nil
}
func decrypt(secret *secret, key *key) (string, error) {
aesCipher, err := aes.NewCipher(key.cipherKey)
if err != nil {
return "", err
}
plainText := make([]byte, len(secret.data))
aesBlock := cipher.NewCTR(aesCipher, key.iv)
aesBlock.XORKeyStream(plainText, secret.data)
result, err := unpad(plainText)
if err != nil {
return "", err
}
return string(result), nil
}
func pad(src []byte) []byte {
padlen := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padlen)}, padlen)
return append(src, padtext...)
}
func unpad(src []byte) ([]byte, error) {
length := len(src)
padlen := int(src[length-1])
if padlen > length {
return nil, ErrInvalidPadding
}
return src[:(length - padlen)], nil
}