61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
package license
|
|
|
|
import (
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/asn1"
|
|
"encoding/base64"
|
|
"math/big"
|
|
)
|
|
|
|
var privateKey *ecdsa.PrivateKey
|
|
|
|
func init() {
|
|
var err error
|
|
privateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
// ecdsaSignature 是 ASN.1 编码中使用的结构体
|
|
type ecdsaSignature struct {
|
|
R, S *big.Int
|
|
}
|
|
|
|
func SignPayload(message []byte) (string, error) {
|
|
hash := sha256.Sum256(message)
|
|
r, s, err := ecdsa.Sign(rand.Reader, privateKey, hash[:])
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
sig, err := asn1.Marshal(ecdsaSignature{r, s})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.StdEncoding.EncodeToString(sig), nil
|
|
}
|
|
|
|
func VerifySignature(pub *ecdsa.PublicKey, message []byte, signatureBase64 string) bool {
|
|
sigBytes, err := base64.StdEncoding.DecodeString(signatureBase64)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
var sig ecdsaSignature
|
|
_, err = asn1.Unmarshal(sigBytes, &sig)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
hash := sha256.Sum256(message)
|
|
return ecdsa.Verify(pub, hash[:], sig.R, sig.S)
|
|
}
|
|
|
|
func GetPublicKey() *ecdsa.PublicKey {
|
|
return &privateKey.PublicKey
|
|
}
|