/
sha_with_rsa.go
80 lines (68 loc) · 1.92 KB
/
sha_with_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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package sign
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"github.com/pjoc-team/base-service/pkg/logger"
)
func SignPKCS8(src []byte, privateKey string, hash crypto.Hash) ([]byte, error) {
var h = hash.New()
h.Write(src)
var hashed = h.Sum(nil)
var err error
bytes, _ := base64.StdEncoding.DecodeString(privateKey)
pri, err := x509.ParsePKCS8PrivateKey(bytes)
if err != nil {
logger.Log.Errorf("Parse private key with error: %v", err.Error())
return nil, err
}
//rsa.Sign
return rsa.SignPKCS1v15(rand.Reader, pri.(*rsa.PrivateKey), hash, hashed)
}
func SignPKCS1v15WithStringKey(src []byte, privateKeyString string, hash crypto.Hash) ([]byte, error) {
privateKey := ParsePrivateKey(privateKeyString)
return SignPKCS1v15(src, privateKey, hash)
}
func VerifyPKCS1v15WithStringKey(src, sig []byte, publicKeyString string, hash crypto.Hash) error {
publicKey := ParsePublicKey(publicKeyString)
return VerifyPKCS1v15(src, sig, publicKey, hash)
}
func SignPKCS1v15(src, privateKey []byte, hash crypto.Hash) ([]byte, error) {
var h = hash.New()
h.Write(src)
var hashed = h.Sum(nil)
var err error
var block *pem.Block
block, _ = pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error")
}
var pri *rsa.PrivateKey
pri, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.SignPKCS1v15(rand.Reader, pri, hash, hashed)
}
func VerifyPKCS1v15(src, sig, publicKey []byte, hash crypto.Hash) error {
var h = hash.New()
h.Write(src)
var hashed = h.Sum(nil)
var err error
var block *pem.Block
block, _ = pem.Decode(publicKey)
if block == nil {
return errors.New("public key error")
}
var pubInterface interface{}
pubInterface, err = x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
var pub = pubInterface.(*rsa.PublicKey)
return rsa.VerifyPKCS1v15(pub, hash, hashed, sig)
}