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