forked from immesys/wave
-
Notifications
You must be signed in to change notification settings - Fork 1
/
signer.go
62 lines (59 loc) · 1.39 KB
/
signer.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
package main
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"time"
"github.com/immesys/wave/storage/simplehttp"
"golang.org/x/crypto/sha3"
)
func ParsePrivateKey(in []byte) (*ecdsa.PrivateKey, error) {
der, trailing := pem.Decode(in)
if len(trailing) != 0 {
return nil, fmt.Errorf("key is invalid")
}
priv, err := x509.ParseECPrivateKey(der.Bytes)
if err != nil {
panic(err)
}
return priv, err
}
func MakeMergePromise(key []byte, valhash []byte, signingkey *ecdsa.PrivateKey) (*simplehttp.MergePromise, error) {
if signingkey == nil {
panic("no signing key!")
}
p := &simplehttp.MergePromiseTBS{
Key: key,
ValHash: valhash,
MergeBy: time.Now().Add(time.Hour).UnixNano() / 1e6,
}
tbs, err := json.Marshal(p)
if err != nil {
return nil, err
}
hash := sha3.Sum256(tbs)
r, s, err := ecdsa.Sign(rand.Reader, signingkey, hash[:])
if err != nil {
return nil, err
}
return &simplehttp.MergePromise{
TBS: tbs,
SigR: r,
SigS: s,
}, nil
}
func VerifyMergePromise(mp *simplehttp.MergePromise, publickey *ecdsa.PublicKey) (*simplehttp.MergePromiseTBS, error) {
hash := sha3.Sum256(mp.TBS)
if !ecdsa.Verify(publickey, hash[:], mp.SigR, mp.SigS) {
return nil, fmt.Errorf("signature is invalid")
}
mptbs := &simplehttp.MergePromiseTBS{}
err := json.Unmarshal(mp.TBS, &mptbs)
if err != nil {
return nil, err
}
return mptbs, nil
}