-
Notifications
You must be signed in to change notification settings - Fork 58
/
rsa.go
272 lines (224 loc) · 5.71 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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package hltool
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"errors"
"io"
"io/ioutil"
"os"
)
const (
// RSAAlgorithmSign RSA签名算法
RSAAlgorithmSign = crypto.SHA256
)
// NewRSAFile 生成密钥对文件
// pubKeyFilename: 公钥文件名 priKeyFilename: 私钥文件名 kekeyLength: 密钥长度
func NewRSAFile(pubKeyFilename, priKeyFilename string, keyLength int) error {
if pubKeyFilename == "" {
pubKeyFilename = "id_rsa.pub"
}
if priKeyFilename == "" {
priKeyFilename = "id_rsa"
}
if keyLength == 0 || keyLength < 1024 {
keyLength = 1024
}
// 创建公钥文件
pubWriter, err := os.Create(pubKeyFilename)
if err != nil {
return err
}
defer pubWriter.Close()
// 创建私钥文件
priWriter, err := os.Create(priKeyFilename)
if err != nil {
return err
}
defer priWriter.Close()
// 生成密钥对
err = WriteRSAKeyPair(pubWriter, priWriter, keyLength)
if err != nil {
return err
}
return nil
}
// NewRSAString 生成密钥对字符串
// keyLength 密钥的长度
func NewRSAString(keyLength int) (string, string, error) {
if keyLength == 0 || keyLength < 1024 {
keyLength = 1024
}
bufPub := make([]byte, 1024*5)
pubuffer := bytes.NewBuffer(bufPub)
bufPri := make([]byte, 1024*5)
pribuffer := bytes.NewBuffer(bufPri)
err := WriteRSAKeyPair(pubuffer, pribuffer, keyLength)
if err != nil {
return "", "", nil
}
return pubuffer.String(), pribuffer.String(), nil
}
// WriteRSAKeyPair 生成RSA密钥对
func WriteRSAKeyPair(publicKeyWriter, privateKeyWriter io.Writer, keyLength int) error {
// 生成私钥文件
privateKey, err := rsa.GenerateKey(rand.Reader, keyLength)
if err != nil {
return err
}
derStream := MarshalPKCS8PrivateKey(privateKey)
block := &pem.Block{
Type: "PRIVATE KEY",
Bytes: derStream,
}
err = pem.Encode(privateKeyWriter, block)
if err != nil {
return err
}
// 生成公钥文件
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
err = pem.Encode(publicKeyWriter, block)
if err != nil {
return err
}
return nil
}
// ReadRSAKeyPair 读取RSA密钥对
// pubKeyFilename: 公钥文件名称 priKeyFilename: 私钥文件名
func ReadRSAKeyPair(pubKeyFilename, priKeyFilename string) ([]byte, []byte, error) {
pub, err := ioutil.ReadFile(pubKeyFilename)
if err != nil {
return nil, nil, err
}
pri, err := ioutil.ReadFile(priKeyFilename)
if err != nil {
return nil, nil, err
}
return pub, pri, nil
}
// GoRSA RSA加密解密
type GoRSA struct {
PublicKey *rsa.PublicKey
PrivateKey *rsa.PrivateKey
}
// NewGoRSA 初始化 GoRSA对象
func NewGoRSA(pubKeyFilename, priKeyFilename string) (*GoRSA, error) {
publicKey, privateKey, err := ReadRSAKeyPair(pubKeyFilename, priKeyFilename)
if err != nil {
return nil, err
}
block, _ := pem.Decode(publicKey)
if block == nil {
return nil, errors.New("public key error")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pub := pubInterface.(*rsa.PublicKey)
block, _ = pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error")
}
priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
pri, ok := priv.(*rsa.PrivateKey)
if ok {
return &GoRSA{
PublicKey: pub,
PrivateKey: pri,
}, nil
}
return nil, errors.New("private key not supported")
}
// PublicEncrypt 公钥加密
func (r *GoRSA) PublicEncrypt(data []byte) ([]byte, error) {
partLen := r.PublicKey.N.BitLen()/8 - 11
chunks := split(data, partLen)
buffer := bytes.NewBufferString("")
for _, chunk := range chunks {
bytes, err := rsa.EncryptPKCS1v15(rand.Reader, r.PublicKey, chunk)
if err != nil {
return nil, err
}
buffer.Write(bytes)
}
return buffer.Bytes(), nil
}
// PrivateDecrypt 私钥解密
func (r *GoRSA) PrivateDecrypt(encrypted []byte) ([]byte, error) {
partLen := r.PublicKey.N.BitLen() / 8
chunks := split(encrypted, partLen)
buffer := bytes.NewBufferString("")
for _, chunk := range chunks {
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, r.PrivateKey, chunk)
if err != nil {
return nil, err
}
buffer.Write(decrypted)
}
return buffer.Bytes(), nil
}
// Sign 数据进行签名
func (r *GoRSA) Sign(data string) (string, error) {
h := RSAAlgorithmSign.New()
h.Write([]byte(data))
hashed := h.Sum(nil)
sign, err := rsa.SignPKCS1v15(rand.Reader, r.PrivateKey, RSAAlgorithmSign, hashed)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(sign), err
}
// Verify 数据验证签名
func (r *GoRSA) Verify(data string, sign string) error {
h := RSAAlgorithmSign.New()
h.Write([]byte(data))
hashed := h.Sum(nil)
decodedSign, err := base64.RawURLEncoding.DecodeString(sign)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(r.PublicKey, RSAAlgorithmSign, hashed, decodedSign)
}
// MarshalPKCS8PrivateKey 私钥解析
func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) []byte {
info := struct {
Version int
PrivateKeyAlgorithm []asn1.ObjectIdentifier
PrivateKey []byte
}{}
info.Version = 0
info.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
info.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
info.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
k, _ := asn1.Marshal(info)
return k
}
func split(buf []byte, lim int) [][]byte {
var chunk []byte
chunks := make([][]byte, 0, len(buf)/lim+1)
for len(buf) >= lim {
chunk, buf = buf[:lim], buf[lim:]
chunks = append(chunks, chunk)
}
if len(buf) > 0 {
chunks = append(chunks, buf[:len(buf)])
}
return chunks
}