go-nostr/keys.go

40 lines
727 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"
"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)
_, err := io.ReadFull(rand.Reader, b)
if 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 hex.EncodeToString(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
}