forked from farmerx/gorsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.go
94 lines (82 loc) · 2.27 KB
/
rsa.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
package gorsa
import (
"bytes"
"crypto/rsa"
"errors"
"io/ioutil"
)
var RSA = &RSASecurity{}
type RSASecurity struct {
pubStr string //公钥字符串
priStr string //私钥字符串
pubkey *rsa.PublicKey //公钥
prikey *rsa.PrivateKey //私钥
}
// 设置公钥
func (rsas *RSASecurity) SetPublicKey(pubStr string) (err error) {
rsas.pubStr = pubStr
rsas.pubkey, err = rsas.GetPublickey()
return err
}
// 设置私钥
func (rsas *RSASecurity) SetPrivateKey(priStr string) (err error) {
rsas.priStr = priStr
rsas.prikey, err = rsas.GetPrivatekey()
return err
}
// *rsa.PublicKey
func (rsas *RSASecurity) GetPrivatekey() (*rsa.PrivateKey, error) {
return getPriKey([]byte(rsas.priStr))
}
// *rsa.PrivateKey
func (rsas *RSASecurity) GetPublickey() (*rsa.PublicKey, error) {
return getPubKey([]byte(rsas.pubStr))
}
// 公钥加密
func (rsas *RSASecurity) PubKeyENCTYPT(input []byte) ([]byte, error) {
if rsas.pubkey == nil {
return []byte(""), errors.New(`Please set the public key in advance`)
}
output := bytes.NewBuffer(nil)
err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, true)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
// 公钥解密
func (rsas *RSASecurity) PubKeyDECRYPT(input []byte) ([]byte, error) {
if rsas.pubkey == nil {
return []byte(""), errors.New(`Please set the public key in advance`)
}
output := bytes.NewBuffer(nil)
err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, false)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
// 私钥加密
func (rsas *RSASecurity) PriKeyENCTYPT(input []byte) ([]byte, error) {
if rsas.prikey == nil {
return []byte(""), errors.New(`Please set the private key in advance`)
}
output := bytes.NewBuffer(nil)
err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, true)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}
// 私钥解密
func (rsas *RSASecurity) PriKeyDECRYPT(input []byte) ([]byte, error) {
if rsas.prikey == nil {
return []byte(""), errors.New(`Please set the private key in advance`)
}
output := bytes.NewBuffer(nil)
err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, false)
if err != nil {
return []byte(""), err
}
return ioutil.ReadAll(output)
}