forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 1
/
signer.go
108 lines (93 loc) · 2.36 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
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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package signer
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"io/ioutil"
"math/big"
"github.com/hyperledger/fabric/bccsp/utils"
"github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric/protos/msp"
proto_utils "github.com/hyperledger/fabric/protos/utils"
"github.com/pkg/errors"
)
// Config holds the configuration for
// creation of a Signer
type Config struct {
MSPID string
IdentityPath string
KeyPath string
}
// Signer signs messages.
// TODO: Ideally we'd use an MSP to be agnostic, but since it's impossible to
// initialize an MSP without a CA cert that signs the signing identity,
// this will do for now.
type Signer struct {
key *ecdsa.PrivateKey
Creator []byte
}
// NewSigner creates a new Signer out of the given configuration
func NewSigner(conf Config) (*Signer, error) {
sId, err := serializeIdentity(conf.IdentityPath, conf.MSPID)
if err != nil {
return nil, errors.WithStack(err)
}
key, err := loadPrivateKey(conf.KeyPath)
if err != nil {
return nil, errors.WithStack(err)
}
return &Signer{
Creator: sId,
key: key,
}, nil
}
func serializeIdentity(clientCert string, mspID string) ([]byte, error) {
b, err := ioutil.ReadFile(clientCert)
if err != nil {
return nil, errors.WithStack(err)
}
sId := &msp.SerializedIdentity{
Mspid: mspID,
IdBytes: b,
}
return proto_utils.MarshalOrPanic(sId), nil
}
func (si *Signer) Sign(msg []byte) ([]byte, error) {
digest := util.ComputeSHA256(msg)
return signECDSA(si.key, digest)
}
func loadPrivateKey(file string) (*ecdsa.PrivateKey, error) {
b, err := ioutil.ReadFile(file)
if err != nil {
return nil, errors.WithStack(err)
}
bl, _ := pem.Decode(b)
key, err := x509.ParsePKCS8PrivateKey(bl.Bytes)
if err != nil {
return nil, errors.WithStack(err)
}
return key.(*ecdsa.PrivateKey), nil
}
func signECDSA(k *ecdsa.PrivateKey, digest []byte) (signature []byte, err error) {
r, s, err := ecdsa.Sign(rand.Reader, k, digest)
if err != nil {
return nil, err
}
s, _, err = utils.ToLowS(&k.PublicKey, s)
if err != nil {
return nil, err
}
return marshalECDSASignature(r, s)
}
func marshalECDSASignature(r, s *big.Int) ([]byte, error) {
return asn1.Marshal(ECDSASignature{r, s})
}
type ECDSASignature struct {
R, S *big.Int
}