rsa_encryption.go
1.1 KB
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
package socialwork_sdk
import (
"crypto"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
)
func rsaSignWithMd5Hex(data string, prvKey string) (string, error) {
block, _ := pem.Decode([]byte(prvKey))
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
}
md5 := md5.New()
md5.Write([]byte(data))
hash := md5.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey.(*rsa.PrivateKey), crypto.MD5, hash[:])
if err != nil {
return "", err
}
out := base64.StdEncoding.EncodeToString(signature)
return out, nil
}
func rsaVerifySignWithMd5Base64(originalData, signData, pubKey string) error {
sign, err := base64.StdEncoding.DecodeString(signData)
if err != nil {
return err
}
block, _ := pem.Decode([]byte(pubKey))
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
hash := md5.New()
hash.Write([]byte(originalData))
err = rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.MD5, hash.Sum(nil), sign)
if err != nil {
return err
}
return nil
}