This repository was archived by the owner on Aug 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjectsig.go
84 lines (67 loc) · 1.67 KB
/
objectsig.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
package objectsig
import (
"bytes"
"github.com/libp2p/go-libp2p-crypto"
mh "github.com/multiformats/go-multihash"
"github.com/pkg/errors"
)
// NewSignature attempts to sign some data.
func NewSignature(priv crypto.PrivKey, data []byte) (*Signature, error) {
sign, err := priv.Sign(data)
if err != nil {
return nil, err
}
pubKey := priv.GetPublic()
pubKeyBytes, err := pubKey.Bytes()
if err != nil {
return nil, err
}
kmh, err := mh.Sum(pubKeyBytes, mh.SHA2_256, -1)
if err != nil {
return nil, err
}
return &Signature{KeyMultihash: kmh, Signature: sign}, nil
}
// MatchesPublicKey checks to see if a signature matches a public key.
// Also checked in Verify.
func (s *Signature) MatchesPublicKey(pub crypto.PubKey) error {
pubData, err := pub.Bytes()
if err != nil {
return err
}
keyMulti, err := mh.Decode(s.GetKeyMultihash())
if err != nil {
return err
}
ourMh, err := mh.Sum(pubData, keyMulti.Code, keyMulti.Length)
if err != nil {
return err
}
// TODO: find a better way to derive digest without encoding it.
ourMhDec, err := mh.Decode(ourMh)
if err != nil {
return err
}
if bytes.Compare(ourMhDec.Digest, keyMulti.Digest) != 0 {
keyMultiC, err := mh.Cast(s.GetKeyMultihash())
if err != nil {
return err
}
return errors.Errorf("hash mismatch: %s != %s", ourMh.B58String(), keyMultiC.B58String())
}
return nil
}
// Verify checks the signature.
func (s *Signature) Verify(pub crypto.PubKey, data []byte) error {
if err := s.MatchesPublicKey(pub); err != nil {
return err
}
ok, err := pub.Verify(data, s.GetSignature())
if err != nil {
return err
}
if !ok {
return errors.New("signature did not match")
}
return nil
}