license-server/license/crypto.go

48 lines
1.0 KiB
Go

package license
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
)
var (
privateKey *ecdsa.PrivateKey
)
func init() {
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
}
sig := append(r.Bytes(), s.Bytes()...)
return base64.StdEncoding.EncodeToString(sig), nil
}
func VerifySignature(pub *rsa.PublicKey, message []byte, signatureBase64 string) bool {
signature, err := base64.StdEncoding.DecodeString(signatureBase64)
if err != nil {
return false
}
hashed := sha256.Sum256(message)
err = rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed[:], signature)
return err == nil
}
func ExportPublicKeyPEM() string {
pubKeyBytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubKeyBytes}))
}