-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.go
255 lines (212 loc) · 5.3 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
package rsa
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"io"
"github.com/LonelyPale/goutils/errors"
)
const (
CharSet = "UTF-8"
Base64Format = "UrlSafeNoPadding"
AlgorithmKeyType = "PKCS1"
AlgorithmSign = crypto.SHA256
Bits = 2048
)
var Base64Encoding *base64.Encoding
func init() {
Base64Encoding = base64.RawURLEncoding
}
type XRsa struct {
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
}
func CreateKeysToBase64(keyLengths ...int) (string, string, error) {
pubKey := bytes.NewBuffer(make([]byte, 0))
priKey := bytes.NewBuffer(make([]byte, 0))
if err := CreateKeys(pubKey, priKey, keyLengths...); err != nil {
return "", "", err
}
return pubKey.String(), priKey.String(), nil
}
func CreateKeysToBytes(keyLengths ...int) ([]byte, []byte, error) {
pubKey := bytes.NewBuffer(make([]byte, 0))
priKey := bytes.NewBuffer(make([]byte, 0))
if err := CreateKeys(pubKey, priKey, keyLengths...); err != nil {
return nil, nil, err
}
return pubKey.Bytes(), priKey.Bytes(), nil
}
// 生成密钥对
func CreateKeys(publicKeyWriter, privateKeyWriter io.Writer, keyLengths ...int) error {
var bits int
if len(keyLengths) > 0 && keyLengths[0] > 0 {
bits = keyLengths[0]
} else {
bits = Bits
}
// 生成私钥文件, bits位数长度
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA 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: "RSA PUBLIC KEY",
Bytes: derPkix,
}
err = pem.Encode(publicKeyWriter, block)
if err != nil {
return err
}
return nil
}
func NewXRsa(publicKey []byte, privateKey []byte) (*XRsa, error) {
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!")
}
pri, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return &XRsa{
publicKey: pub,
privateKey: pri,
}, nil
}
// 公钥加密
func (r *XRsa) Encrypt(data []byte) ([]byte, error) {
partLen := r.publicKey.N.BitLen()/8 - 11
chunks := split(data, partLen)
buffer := bytes.NewBuffer([]byte{})
for _, chunk := range chunks {
encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, r.publicKey, chunk)
if err != nil {
return nil, err
}
buffer.Write(encrypted)
}
return buffer.Bytes(), nil
}
// 私钥解密
func (r *XRsa) Decrypt(encrypted []byte) ([]byte, error) {
partLen := r.publicKey.N.BitLen() / 8
chunks := split(encrypted, partLen)
buffer := bytes.NewBuffer([]byte{})
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
}
// 私钥签名
func (r *XRsa) Sign(data []byte) ([]byte, error) {
h := AlgorithmSign.New()
if _, err := h.Write(data); err != nil {
return nil, err
}
hashed := h.Sum(nil)
sign, err := rsa.SignPKCS1v15(rand.Reader, r.privateKey, AlgorithmSign, hashed)
if err != nil {
return nil, err
}
return sign, nil
}
// 公钥验签
func (r *XRsa) Verify(data []byte, sign []byte) error {
h := AlgorithmSign.New()
if _, err := h.Write(data); err != nil {
return err
}
hashed := h.Sum(nil)
return rsa.VerifyPKCS1v15(r.publicKey, AlgorithmSign, hashed, sign)
}
func (r *XRsa) EncryptToBase64(data []byte) (string, error) {
bs, err := r.Encrypt(data)
if err != nil {
return "", err
}
return Base64Encoding.EncodeToString(bs), nil
}
func (r *XRsa) DecryptFromBase64(encrypted string) ([]byte, error) {
raw, err := Base64Encoding.DecodeString(encrypted)
if err != nil {
return nil, err
}
return r.Decrypt(raw)
}
// 数据签名
func (r *XRsa) SignToBase64(data []byte) (string, error) {
sign, err := r.Sign(data)
if err != nil {
return "", err
}
return Base64Encoding.EncodeToString(sign), nil
}
func (r *XRsa) VerifyFromBase64(data []byte, sign string) error {
decodedSign, err := Base64Encoding.DecodeString(sign)
if err != nil {
return err
}
return r.Verify(data, decodedSign)
}
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
}
func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) ([]byte, error) {
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, err := asn1.Marshal(info)
if err != nil {
return nil, err
}
return k, nil
}