forked from Oskang09/securfile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecrypt.go
More file actions
60 lines (49 loc) · 1.4 KB
/
decrypt.go
File metadata and controls
60 lines (49 loc) · 1.4 KB
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
package securfile
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"io/ioutil"
"strings"
)
var (
ErrInvalidEncryptedValue = errors.New("securfile: invalid encrypted value")
ErrInvalidNonceValue = errors.New("securfile: invalid nonce value")
)
func decrypt(cipherValue string, nonceKey string, cipherKey string, authKey string) (string, error) {
bytes, err := base64.StdEncoding.DecodeString(cipherValue)
if err != nil {
return "", err
}
block, err := aes.NewCipher([]byte(cipherKey))
if err != nil {
return "", err
}
aesgcm, err := cipher.NewGCMWithNonceSize(block, len(nonceKey))
if err != nil {
return "", err
}
text, err := aesgcm.Open(nil, []byte(nonceKey), bytes, []byte(authKey))
if err != nil {
return "", err
}
return string(text), nil
}
func DecryptString(cipherValue string, cipherKey string, authKey string) (string, error) {
ciphers := strings.Split(cipherValue, ",")
if len(ciphers) != 2 {
return "", ErrInvalidEncryptedValue
}
return decrypt(ciphers[1], ciphers[0], cipherKey, authKey)
}
func DecryptBytes(cipherBytes []byte, cipherKey string, authKey string) (string, error) {
return DecryptString(string(cipherBytes), cipherKey, authKey)
}
func DecryptFile(file string, cipherKey string, authKey string) (string, error) {
bytes, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return DecryptBytes(bytes, cipherKey, authKey)
}