-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
rsa.go
38 lines (35 loc) · 1022 Bytes
/
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
package secu
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"github.com/toolkits/pkg/logger"
)
func Decrypt(cipherText string, privateKeyByte []byte, password string) (decrypted string, err error) {
decodeCipher, _ := base64.StdEncoding.DecodeString(cipherText)
//pem解码
block, _ := pem.Decode(privateKeyByte)
var privateKey *rsa.PrivateKey
if password != "" {
decryptedPrivateKeyBytes, err := x509.DecryptPEMBlock(block, []byte(password))
if err != nil {
logger.Error("Failed to DecryptPEMBlock:", err)
return "", err
}
privateKey, err = x509.ParsePKCS1PrivateKey(decryptedPrivateKeyBytes)
} else {
privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
}
if err != nil {
logger.Error("Failed to parse private key:", err)
return "", err
}
decryptedByte, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decodeCipher)
if err != nil {
logger.Error("Failed to decrypt data:", err)
return "", err
}
return string(decryptedByte), err
}