forked from cgorenflo/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
77 lines (61 loc) · 1.71 KB
/
message.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package entities
import (
"encoding/json"
"github.com/pkg/errors"
)
// SignedMessage is a simple struct that contains space
// for a payload and a signature over it, and convenience
// functions to sign, verify, marshal and unmarshal
type SignedMessage struct {
// ID contains a description of the entity signing this message
ID []byte `json:"id"`
// Payload contains the message that is signed
Payload []byte `json:"payload"`
// Sig contains a signature over ID and Payload
Sig []byte `json:"sig"`
}
// Sign signs the SignedMessage and stores the signature in the Sig field
func (m *SignedMessage) Sign(signer Signer) error {
if signer == nil {
return errors.New("nil signer")
}
m.Sig = nil
bytes, err := json.Marshal(m)
if err != nil {
return errors.Wrap(err, "sign error: json.Marshal returned")
}
sig, err := signer.Sign(bytes)
if err != nil {
return errors.WithMessage(err, "sign error: signer.Sign returned")
}
m.Sig = sig
return nil
}
// Verify verifies the signature over Payload stored in Sig
func (m *SignedMessage) Verify(verifier Signer) (bool, error) {
if verifier == nil {
return false, errors.New("nil verifier")
}
sig := m.Sig
m.Sig = nil
defer func() {
m.Sig = sig
}()
bytes, err := json.Marshal(m)
if err != nil {
return false, errors.Wrap(err, "sign error: json.Marshal returned")
}
return verifier.Verify(sig, bytes)
}
// ToBytes serializes the intance to bytes
func (m *SignedMessage) ToBytes() ([]byte, error) {
return json.Marshal(m)
}
// FromBytes populates the instance from the supplied byte array
func (m *SignedMessage) FromBytes(d []byte) error {
return json.Unmarshal(d, m)
}