|
@@ -1,6 +1,7 @@
|
|
package spiderutil
|
|
package spiderutil
|
|
|
|
|
|
import (
|
|
import (
|
|
|
|
+ "crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"encoding/pem"
|
|
@@ -34,3 +35,32 @@ func DecryptWithPrivateKey(ciphertext, privateKeyStr []byte) []byte {
|
|
// 返回解密后的原始数据
|
|
// 返回解密后的原始数据
|
|
return plaintext
|
|
return plaintext
|
|
}
|
|
}
|
|
|
|
+
|
|
|
|
+//rsa公钥加密
|
|
|
|
+func EncryptWithPublicKey(ciphertext, privateKeyStr []byte) []byte {
|
|
|
|
+ // 将PEM编码的私钥解码为x509格式的数据块
|
|
|
|
+ block, _ := pem.Decode(privateKeyStr)
|
|
|
|
+ if block == nil {
|
|
|
|
+ return nil
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // 解析DER编码的私钥,得到一个asn1.BitString类型的数据
|
|
|
|
+ parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes)
|
|
|
|
+ if err != nil {
|
|
|
|
+ return nil
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // 将解析后的公钥转换为RSA公钥类型
|
|
|
|
+ privateKey, ok := parsedKey.(*rsa.PublicKey)
|
|
|
|
+ if !ok {
|
|
|
|
+ return nil
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // 使用RSA公钥加密数据
|
|
|
|
+ plaintext, err := rsa.EncryptPKCS1v15(rand.Reader, privateKey, ciphertext)
|
|
|
|
+ if err != nil {
|
|
|
|
+ return nil
|
|
|
|
+ }
|
|
|
|
+ // 返回加密后数据
|
|
|
|
+ return plaintext
|
|
|
|
+}
|