-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (108 loc) · 2.54 KB
/
main.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"log"
"os"
btcec "github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/urfave/cli/v2"
)
func main() {
app := &cli.App{
Commands: []*cli.Command{
{
Name: "pubkey",
Usage: "generate schnorr pubkey from private key",
Action: func(cCtx *cli.Context) error {
b, err := base64.StdEncoding.DecodeString(cCtx.Args().First())
if err != nil {
return err
}
priv, _ := btcec.PrivKeyFromBytes(b)
pub := schnorr.SerializePubKey(priv.PubKey())
fmt.Printf("%s\n", base64.StdEncoding.EncodeToString(pub))
return nil
},
},
{
Name: "signb64",
Usage: "sign a base64 document",
Action: func(cCtx *cli.Context) error {
doc, err := base64.StdEncoding.DecodeString(cCtx.Args().Get(1))
if err != nil {
return err
}
return sign(cCtx, doc)
},
},
{
Name: "sign",
Usage: "sign a string document",
Action: func(cCtx *cli.Context) error {
return sign(cCtx, []byte(cCtx.Args().Get(1)))
},
},
{
Name: "verify",
Usage: "verify a schnorr signature",
Action: func(cCtx *cli.Context) error {
return verify(cCtx, []byte(cCtx.Args().Get(2)))
},
},
{
Name: "verifyb64",
Usage: "verify a schnorr signature",
Action: func(cCtx *cli.Context) error {
doc, err := base64.StdEncoding.DecodeString(cCtx.Args().Get(2))
if err != nil {
return err
}
return verify(cCtx, doc)
},
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func sign(cCtx *cli.Context, doc []byte) error {
b, err := base64.StdEncoding.DecodeString(cCtx.Args().First())
if err != nil {
return err
}
priv, _ := btcec.PrivKeyFromBytes(b)
h := sha256.New()
h.Write(doc)
signature, _ := schnorr.Sign(priv, h.Sum(nil))
fmt.Printf("%s\n", base64.StdEncoding.EncodeToString(signature.Serialize()))
return nil
}
func verify(cCtx *cli.Context, doc []byte) error {
b, err := base64.StdEncoding.DecodeString(cCtx.Args().First())
if err != nil {
return err
}
publicKey, err := schnorr.ParsePubKey(b)
if err != nil {
return err
}
sigBytes, err := base64.StdEncoding.DecodeString(cCtx.Args().Get(1))
if err != nil {
return err
}
signature, err := schnorr.ParseSignature(sigBytes)
if err != nil {
return err
}
h := sha256.New()
h.Write(doc)
if !signature.Verify(h.Sum(nil), publicKey) {
fmt.Printf("signature does not verify\n")
os.Exit(1)
}
fmt.Printf("signature verifies\n")
return nil
}