github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/integration/nwo/signingid.go (about)

     1  /*
     2  Copyright hechain. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package nwo
     8  
     9  import (
    10  	"crypto/ecdsa"
    11  	"crypto/rand"
    12  	"crypto/sha256"
    13  	"crypto/x509"
    14  	"encoding/pem"
    15  	"fmt"
    16  	"io/ioutil"
    17  
    18  	"github.com/golang/protobuf/proto"
    19  	"github.com/hechain20/hechain/bccsp/utils"
    20  	"github.com/hyperledger/fabric-protos-go/msp"
    21  )
    22  
    23  // A SigningIdentity represents an MSP signing identity.
    24  type SigningIdentity struct {
    25  	CertPath string
    26  	KeyPath  string
    27  	MSPID    string
    28  }
    29  
    30  // Serialize returns the probobuf encoding of an msp.SerializedIdenity.
    31  func (s *SigningIdentity) Serialize() ([]byte, error) {
    32  	cert, err := ioutil.ReadFile(s.CertPath)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	return proto.Marshal(&msp.SerializedIdentity{
    37  		Mspid:   s.MSPID,
    38  		IdBytes: cert,
    39  	})
    40  }
    41  
    42  // Sign computes a SHA256 message digest, signs it with the associated private
    43  // key, and returns the signature after low-S normlization.
    44  func (s *SigningIdentity) Sign(msg []byte) ([]byte, error) {
    45  	digest := sha256.Sum256(msg)
    46  	pemKey, err := ioutil.ReadFile(s.KeyPath)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	block, _ := pem.Decode(pemKey)
    51  	if block.Type != "EC PRIVATE KEY" && block.Type != "PRIVATE KEY" {
    52  		return nil, fmt.Errorf("file %s does not contain a private key", s.KeyPath)
    53  	}
    54  	key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	eckey, ok := key.(*ecdsa.PrivateKey)
    59  	if !ok {
    60  		return nil, fmt.Errorf("unexpected key type: %T", key)
    61  	}
    62  	r, _s, err := ecdsa.Sign(rand.Reader, eckey, digest[:])
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	sig, err := utils.MarshalECDSASignature(r, _s)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	return utils.SignatureToLowS(&eckey.PublicKey, sig)
    71  }