-
Notifications
You must be signed in to change notification settings - Fork 3
/
encrypt.go
41 lines (36 loc) · 858 Bytes
/
encrypt.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
package rsaKit
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"github.com/richelieu-yang/chimera/v3/src/core/sliceKit"
"github.com/richelieu-yang/chimera/v3/src/crypto/base64Kit"
)
// Encrypt 公钥加密.
/*
支持: PKCS1、PKCS8.
*/
func Encrypt(data, pemData []byte) ([]byte, error) {
if err := sliceKit.AssertNotEmpty(pemData, "pemData"); err != nil {
return nil, err
}
// 公钥
publicKey, err := ParsePublicKeyFromPem(pemData)
if err != nil {
return nil, err
}
// 分块加密
buffer := bytes.NewBufferString("")
partLen := publicKey.N.BitLen()/8 - 11
chunks := sliceKit.Split(data, partLen)
for _, chunk := range chunks {
tmp, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, chunk)
if err != nil {
return nil, err
}
buffer.Write(tmp)
}
data = buffer.Bytes()
// base64编码
return base64Kit.Encode(data), nil
}