/
cipher.go
79 lines (66 loc) · 1.55 KB
/
cipher.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
package crypto
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"io/fs"
"io/ioutil"
"github.com/soderasen-au/go-common/util"
)
func InternalEncypt(text []byte) ([]byte, error) {
cipher, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &InternalPrivateKey.PublicKey, text, nil)
if err != nil {
return nil, err
}
return cipher, nil
}
func InternalDecrypt(cipher []byte) ([]byte, error) {
text, err := InternalPrivateKey.Decrypt(nil, cipher, &rsa.OAEPOptions{Hash: crypto.SHA256})
if err != nil {
return nil, err
}
return text, nil
}
type CipherFile struct {
File string `json:"file" yaml:"file" bson:"file" csv:"file"`
Text string `json:"-" yaml:"-" bson:"-" csv:"-"`
}
func NewCipherFile(file string) *CipherFile {
return &CipherFile{
File: file,
Text: "",
}
}
func (c CipherFile) WriteToFile() *util.Result {
if c.Text == "" {
return util.MsgError("Check", "empty text")
}
if c.File == "" {
return util.MsgError("Check", "empty file name")
}
cipher, err := InternalEncypt([]byte(c.Text))
if err != nil {
return util.Error("Encrypt", err)
}
err = ioutil.WriteFile(c.File, cipher, fs.ModePerm)
if err != nil {
return util.Error("WriteFile", err)
}
return nil
}
func (c *CipherFile) ReadFromFile() *util.Result {
if c.File == "" {
return util.MsgError("Check", "empty file name")
}
pwbytes, err := ioutil.ReadFile(c.File)
if err != nil {
return util.Error("ReadFile", err)
}
pw, err := InternalDecrypt(pwbytes)
if err != nil {
return util.Error("InternalDecrypt", err)
}
c.Text = string(pw)
return nil
}