This commit is contained in:
hailin 2025-06-13 21:58:25 +08:00
parent 60e3d8b873
commit 0a294da37e
1 changed files with 26 additions and 29 deletions

View File

@ -1,50 +1,47 @@
package license package license
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic" "crypto/elliptic"
"crypto/rand" "crypto/rand"
"crypto/sha256" "crypto/sha256"
"crypto/x509" "crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/pem"
"encoding/pem" "math/big"
"math/big"
"time"
) )
var ( var (
privateKey *ecdsa.PrivateKey privateKey *ecdsa.PrivateKey
) )
func init() { func init() {
privateKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) privateKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
} }
func SignPayload(payload []byte) (string, error) { func SignPayload(payload []byte) (string, error) {
hash := sha256.Sum256(payload) hash := sha256.Sum256(payload)
r, s, err := ecdsa.Sign(rand.Reader, privateKey, hash[:]) r, s, err := ecdsa.Sign(rand.Reader, privateKey, hash[:])
if err != nil { if err != nil {
return "", err return "", err
} }
sig := append(r.Bytes(), s.Bytes()...) sig := append(r.Bytes(), s.Bytes()...)
return base64.StdEncoding.EncodeToString(sig), nil return base64.StdEncoding.EncodeToString(sig), nil
} }
func VerifySignature(pubKey *ecdsa.PublicKey, payload []byte, signature string) bool { func VerifySignature(pubKey *ecdsa.PublicKey, payload []byte, signature string) bool {
sigBytes, _ := base64.StdEncoding.DecodeString(signature) sigBytes, _ := base64.StdEncoding.DecodeString(signature)
r := big.Int{} r := big.Int{}
s := big.Int{} s := big.Int{}
r.SetBytes(sigBytes[:len(sigBytes)/2]) r.SetBytes(sigBytes[:len(sigBytes)/2])
s.SetBytes(sigBytes[len(sigBytes)/2:]) s.SetBytes(sigBytes[len(sigBytes)/2:])
hash := sha256.Sum256(payload) hash := sha256.Sum256(payload)
return ecdsa.Verify(pubKey, hash[:], &r, &s) return ecdsa.Verify(pubKey, hash[:], &r, &s)
} }
func ExportPublicKeyPEM() string { func ExportPublicKeyPEM() string {
pubKeyBytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey) pubKeyBytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubKeyBytes})) return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubKeyBytes}))
} }