github.com/canhui/fabric_ca2_2@v2.0.0-alpha+incompatible/lib/client/credential/x509/signer.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package x509
     8  
     9  import (
    10  	"crypto/x509"
    11  	"fmt"
    12  
    13  	"github.com/hyperledger/fabric-ca/lib/attrmgr"
    14  	"github.com/hyperledger/fabric-ca/util"
    15  	"github.com/hyperledger/fabric/bccsp"
    16  	"github.com/pkg/errors"
    17  )
    18  
    19  // NewSigner is constructor for Signer
    20  func NewSigner(key bccsp.Key, cert []byte) (*Signer, error) {
    21  	s := &Signer{
    22  		key:       key,
    23  		certBytes: cert,
    24  	}
    25  	var err error
    26  	s.cert, err = util.GetX509CertificateFromPEM(s.certBytes)
    27  	if err != nil {
    28  		return nil, errors.WithMessage(err, "Failed to unmarshal X509 certificate bytes")
    29  	}
    30  	s.name = util.GetEnrollmentIDFromX509Certificate(s.cert)
    31  	return s, nil
    32  }
    33  
    34  // Signer represents a signer
    35  // Each identity may have multiple signers, currently one ecert and multiple tcerts
    36  type Signer struct {
    37  	// Private key
    38  	key bccsp.Key
    39  	// Certificate bytes
    40  	certBytes []byte
    41  	// X509 certificate that is constructed from the cert bytes associated with this signer
    42  	cert *x509.Certificate
    43  	// Common name from the certificate associated with this signer
    44  	name string
    45  }
    46  
    47  // Key returns the key bytes of this signer
    48  func (s *Signer) Key() bccsp.Key {
    49  	return s.key
    50  }
    51  
    52  // Cert returns the cert bytes of this signer
    53  func (s *Signer) Cert() []byte {
    54  	return s.certBytes
    55  }
    56  
    57  // GetX509Cert returns the X509 certificate for this signer
    58  func (s *Signer) GetX509Cert() *x509.Certificate {
    59  	return s.cert
    60  }
    61  
    62  // GetName returns common name that is retrieved from the Subject of the certificate
    63  // associated with this signer
    64  func (s *Signer) GetName() string {
    65  	return s.name
    66  }
    67  
    68  // Attributes returns the attributes that are in the certificate
    69  func (s *Signer) Attributes() (*attrmgr.Attributes, error) {
    70  	cert := s.GetX509Cert()
    71  	attrs, err := attrmgr.New().GetAttributesFromCert(cert)
    72  	if err != nil {
    73  		return nil, fmt.Errorf("Failed getting attributes for '%s': %s", s.name, err)
    74  	}
    75  	return attrs, nil
    76  }