-
Notifications
You must be signed in to change notification settings - Fork 106
/
keys.go
49 lines (39 loc) · 903 Bytes
/
keys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package nostr
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"math/big"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
)
func GeneratePrivateKey() string {
params := btcec.S256().Params()
one := new(big.Int).SetInt64(1)
b := make([]byte, params.BitSize/8+8)
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())
}
func GetPublicKey(sk string) (string, error) {
b, err := hex.DecodeString(sk)
if err != nil {
return "", err
}
_, pk := btcec.PrivKeyFromBytes(b)
return hex.EncodeToString(schnorr.SerializePubKey(pk)), nil
}
func IsValidPublicKey(pk string) bool {
if !isLowerHex(pk) {
return false
}
v, _ := hex.DecodeString(pk)
_, err := schnorr.ParsePubKey(v)
return err == nil
}