go-nostr/keys.go

50 lines
903 B
Go
Raw Permalink Normal View History

2022-01-05 10:16:36 -04:00
package nostr
import (
"crypto/rand"
2022-01-05 10:16:36 -04:00
"encoding/hex"
"fmt"
"io"
"math/big"
2022-01-05 10:16:36 -04:00
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
2022-01-05 10:16:36 -04:00
)
func GeneratePrivateKey() string {
params := btcec.S256().Params()
one := new(big.Int).SetInt64(1)
b := make([]byte, params.BitSize/8+8)
2023-06-11 10:48:46 -03:00
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
k := new(big.Int).SetBytes(b)
n := new(big.Int).Sub(params.N, one)
k.Mod(k, n)
k.Add(k, one)
return fmt.Sprintf("%064x", k.Bytes())
2022-01-05 10:16:36 -04:00
}
func GetPublicKey(sk string) (string, error) {
b, err := hex.DecodeString(sk)
2022-01-05 10:16:36 -04:00
if err != nil {
return "", err
2022-01-05 10:16:36 -04:00
}
_, pk := btcec.PrivKeyFromBytes(b)
return hex.EncodeToString(schnorr.SerializePubKey(pk)), nil
2022-01-05 10:16:36 -04:00
}
2024-10-14 16:18:32 -03:00
func IsValidPublicKey(pk string) bool {
if !isLowerHex(pk) {
return false
}
v, _ := hex.DecodeString(pk)
2024-01-18 17:56:54 -03:00
_, err := schnorr.ParsePubKey(v)
return err == nil
}