-
Notifications
You must be signed in to change notification settings - Fork 0
/
public-common.go
executable file
·126 lines (102 loc) · 2.3 KB
/
public-common.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package sqlitehench
import (
"crypto/aes"
"crypto/cipher"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
)
// Decrypt decryptes an array of bytes using the AES algorythm.
func Decrypt(data []byte, passphrase string) ([]byte, error) {
var plain []byte
if len(data) == 0 {
return data, nil
}
key := []byte(createHash(passphrase))
block, err := aes.NewCipher(key)
if err != nil {
return plain, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return plain, err
}
nonceSize := gcm.NonceSize()
if nonceSize > len(data) {
return plain, errors.New("cipher data not found")
}
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plain, err = gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return plain, err
}
return plain, nil
}
// Encrypt encryptes an array of bytes using the AES algorythm.
func Encrypt(plainData []byte, passphrase string) ([]byte, error) {
var cipherData []byte
block, _ := aes.NewCipher([]byte(createHash(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
return cipherData, err
}
nonceBytes := make([]byte, gcm.NonceSize())
cipherData = gcm.Seal(nonceBytes, nonceBytes, plainData, nil)
return cipherData, nil
}
// Encrypt encryptes a file using the AES algorythm.
func EncryptFile(p string, pwdPhrase string) error {
var b []byte
var binc []byte
var err error
if b, err = ioutil.ReadFile(p); err != nil {
return err
}
if binc, err = Encrypt(b, pwdPhrase); err != nil {
return err
}
np := fmt.Sprintf("%s@~%vtmp", p, time.Now().Nanosecond())
f, err := os.Create(np)
if err != nil {
os.Remove(np)
fmt.Println(err)
}
if err = os.Remove(p); err != nil {
return err
}
if err = os.Rename(np, p); err != nil {
return err
}
f.Write(binc)
f.Close()
return nil
}
// DecryptFile decryptes a file using the AES algorythm.
func DecryptFile(p string, pwdPhrase string) error {
var b []byte
var binc []byte
var err error
if b, err = ioutil.ReadFile(p); err != nil {
return err
}
if binc, err = Decrypt(b, pwdPhrase); err != nil {
return err
}
np := fmt.Sprintf("%s@~%vtmp", p, time.Now().Nanosecond())
f, err := os.Create(np)
if err != nil {
os.Remove(np)
return err
}
if err = os.Remove(p); err != nil {
return err
}
if err = os.Rename(np, p); err != nil {
return err
}
f.Write(binc)
f.Close()
return nil
}