forked from hyperledger/fabric
/
signingid.go
71 lines (64 loc) · 1.65 KB
/
signingid.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package nwo
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"github.com/ZihuaZhang/fabric-protos-go/msp"
"github.com/ZihuaZhang/fabric/bccsp/utils"
"github.com/golang/protobuf/proto"
)
// A SigningIdentity represents an MSP signing identity.
type SigningIdentity struct {
CertPath string
KeyPath string
MSPID string
}
// Serialize returns the probobuf encoding of an msp.SerializedIdenity.
func (s *SigningIdentity) Serialize() ([]byte, error) {
cert, err := os.ReadFile(s.CertPath)
if err != nil {
return nil, err
}
return proto.Marshal(&msp.SerializedIdentity{
Mspid: s.MSPID,
IdBytes: cert,
})
}
// Sign computes a SHA256 message digest, signs it with the associated private
// key, and returns the signature after low-S normlization.
func (s *SigningIdentity) Sign(msg []byte) ([]byte, error) {
digest := sha256.Sum256(msg)
pemKey, err := os.ReadFile(s.KeyPath)
if err != nil {
return nil, err
}
block, _ := pem.Decode(pemKey)
if block.Type != "EC PRIVATE KEY" && block.Type != "PRIVATE KEY" {
return nil, fmt.Errorf("file %s does not contain a private key", s.KeyPath)
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
eckey, ok := key.(*ecdsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("unexpected key type: %T", key)
}
r, _s, err := ecdsa.Sign(rand.Reader, eckey, digest[:])
if err != nil {
return nil, err
}
sig, err := utils.MarshalECDSASignature(r, _s)
if err != nil {
return nil, err
}
return utils.SignatureToLowS(&eckey.PublicKey, sig)
}