-
Notifications
You must be signed in to change notification settings - Fork 3
/
decrypt.go
44 lines (39 loc) · 928 Bytes
/
decrypt.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
package rsaKit
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"github.com/richelieu-yang/chimera/v2/src/core/sliceKit"
"github.com/richelieu-yang/chimera/v2/src/crypto/base64Kit"
)
// Decrypt 私钥解密
/*
支持: PKCS1、PKCS8.
*/
func Decrypt(data, pemData []byte, password string) ([]byte, error) {
if err := sliceKit.AssertNotEmpty(pemData, "pemData"); err != nil {
return nil, err
}
// 私钥
privateKey, err := ParsePrivateKeyFromPem(pemData, password)
if err != nil {
return nil, err
}
// base64解码
data, err = base64Kit.Decode(data)
if err != nil {
return nil, err
}
// 分块解密
buffer := bytes.NewBufferString("")
partLen := privateKey.N.BitLen() / 8
chunks := sliceKit.Split(data, partLen)
for _, chunk := range chunks {
tmp, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, chunk)
if err != nil {
return nil, err
}
buffer.Write(tmp)
}
return buffer.Bytes(), nil
}