Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
BitgetLimited
GitHub Repository: BitgetLimited/V3-bitget-api-sdk
Path: blob/master/bitget-golang-sdk-api/internal/common/signer.go
735 views
1
package common
2
3
import (
4
"crypto"
5
"crypto/hmac"
6
"crypto/rand"
7
"crypto/rsa"
8
"crypto/sha256"
9
"crypto/x509"
10
"encoding/base64"
11
"encoding/pem"
12
"errors"
13
"strings"
14
)
15
16
type Signer struct {
17
secretKey []byte
18
}
19
20
func (p *Signer) Init(key string) *Signer {
21
p.secretKey = []byte(key)
22
return p
23
}
24
25
func (p *Signer) Sign(method string, requestPath string, body string, timesStamp string) string {
26
var payload strings.Builder
27
payload.WriteString(timesStamp)
28
payload.WriteString(method)
29
payload.WriteString(requestPath)
30
if body != "" && body != "?" {
31
payload.WriteString(body)
32
}
33
hash := hmac.New(sha256.New, p.secretKey)
34
hash.Write([]byte(payload.String()))
35
result := base64.StdEncoding.EncodeToString(hash.Sum(nil))
36
return result
37
}
38
39
func (p *Signer) SignByRSA(method string, requestPath string, body string, timesStamp string) string {
40
var payload strings.Builder
41
payload.WriteString(timesStamp)
42
payload.WriteString(method)
43
payload.WriteString(requestPath)
44
if body != "" && body != "?" {
45
payload.WriteString(body)
46
}
47
48
sign, _ := RSASign([]byte(payload.String()), p.secretKey, crypto.SHA256)
49
result := base64.StdEncoding.EncodeToString(sign)
50
return result
51
}
52
53
func RSASign(src []byte, priKey []byte, hash crypto.Hash) ([]byte, error) {
54
block, _ := pem.Decode(priKey)
55
if block == nil {
56
return nil, errors.New("key is invalid format")
57
}
58
59
var pkixPrivateKey interface{}
60
var err error
61
if block.Type == "RSA PRIVATE KEY" {
62
pkixPrivateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
63
} else if block.Type == "PRIVATE KEY" {
64
pkixPrivateKey, err = x509.ParsePKCS8PrivateKey(block.Bytes)
65
}
66
67
h := hash.New()
68
_, err = h.Write(src)
69
if err != nil {
70
return nil, err
71
}
72
73
bytes := h.Sum(nil)
74
sign, err := rsa.SignPKCS1v15(rand.Reader, pkixPrivateKey.(*rsa.PrivateKey), hash, bytes)
75
if err != nil {
76
return nil, err
77
}
78
79
return sign, nil
80
}
81
82