-
Notifications
You must be signed in to change notification settings - Fork 5
/
rsa_public_key.go
103 lines (92 loc) · 2.24 KB
/
rsa_public_key.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
package codec
import (
"bytes"
"crypto"
"crypto/md5"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"io/ioutil"
)
// 设置公钥
func NewRSAPublicKey(publicKey []byte) (r *RSAPublicKey, err error) {
r = &RSAPublicKey{}
if publicKey != nil {
err = r.SetPublicKeyBytes(publicKey)
}
return
}
type RSAPublicKey struct {
keyBytes []byte //公钥内容
publicKey *rsa.PublicKey //公钥
}
func (r *RSAPublicKey) SetPublicKeyBytes(publicKey []byte) error {
r.keyBytes = publicKey
_, err := r.GetPublicKey()
return err
}
func (r *RSAPublicKey) SetPublicKey(publicKey *rsa.PublicKey) *RSAPublicKey {
r.publicKey = publicKey
return r
}
// *rsa.PrivateKey
func (r *RSAPublicKey) GetPublicKey() (*rsa.PublicKey, error) {
var err error
if r.publicKey == nil {
r.publicKey, err = getPublicKey(r.keyBytes)
}
return r.publicKey, err
}
// 公钥加密
func (r *RSAPublicKey) Encrypt(input []byte) ([]byte, error) {
if r.publicKey == nil {
return nil, ErrPublicKeyNotSet
}
output := bytes.NewBuffer(nil)
err := publicKeyIO(r.publicKey, bytes.NewReader(input), output, true)
if err != nil {
return nil, err
}
return ioutil.ReadAll(output)
}
// 公钥解密
func (r *RSAPublicKey) Decrypt(input []byte) ([]byte, error) {
if r.publicKey == nil {
return nil, ErrPublicKeyNotSet
}
output := bytes.NewBuffer(nil)
err := publicKeyIO(r.publicKey, bytes.NewReader(input), output, false)
if err != nil {
return nil, err
}
return ioutil.ReadAll(output)
}
/**
* 使用RSAWithMD5验证签名
*/
func (r *RSAPublicKey) VerifySignMd5(data string, signData string) error {
sign, err := base64.StdEncoding.DecodeString(signData)
if err != nil {
return err
}
hash := md5.New()
hash.Write([]byte(data))
return rsa.VerifyPKCS1v15(r.publicKey, crypto.MD5, hash.Sum(nil), sign)
}
/**
* 使用RSAWithSHA1验证签名
*/
func (r *RSAPublicKey) VerifySignSha1(data []byte, sign []byte) error {
hash := sha1.New()
hash.Write(data)
return rsa.VerifyPKCS1v15(r.publicKey, crypto.SHA1, hash.Sum(nil), sign)
}
/**
* 使用RSAWithSHA256验证签名
*/
func (r *RSAPublicKey) VerifySignSha256(data []byte, sign []byte) error {
hash := sha256.New()
hash.Write(data)
return rsa.VerifyPKCS1v15(r.publicKey, crypto.SHA256, hash.Sum(nil), sign)
}