github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/p2p/secure/certificate.go (about)

     1  package secure
     2  
     3  import (
     4  	"crypto/x509"
     5  	"encoding/asn1"
     6  	"encoding/pem"
     7  	"errors"
     8  	"fmt"
     9  	"reflect"
    10  )
    11  
    12  func GetCertFromPem(idBytes []byte) (*x509.Certificate, error) {
    13  	if idBytes == nil {
    14  		return nil, errors.New("getCertFromPem error: nil idBytes")
    15  	}
    16  	// Decode the pem bytes
    17  	pemCert, _ := pem.Decode(idBytes)
    18  	if pemCert == nil {
    19  		return nil, errors.New(fmt.Sprintf("getCertFromPem error: could not decode pem bytes [%v]", idBytes))
    20  	}
    21  	// get a cert
    22  	var cert *x509.Certificate
    23  	cert, err := x509.ParseCertificate(pemCert.Bytes)
    24  	if err != nil {
    25  		return nil, errors.New(fmt.Sprintf(" %v getCertFromPem error: failed to parse x509 cert", err))
    26  	}
    27  	return cert, nil
    28  }
    29  
    30  // getSubjectKeyIdentifierFromCert returns the Subject Key Identifier for the supplied certificate
    31  // Subject Key Identifier is an identifier of the public key of this certificate
    32  func getSubjectKeyIdentifierFromCert(cert *x509.Certificate) ([]byte, error) {
    33  	var SKI []byte
    34  	for _, ext := range cert.Extensions {
    35  		// Subject Key Identifier is identified by the following ASN.1 tag
    36  		// subjectKeyIdentifier (2 5 29 14) (see https://tools.ietf.org/html/rfc3280.html)
    37  		if reflect.DeepEqual(ext.Id, asn1.ObjectIdentifier{2, 5, 29, 14}) {
    38  			_, err := asn1.Unmarshal(ext.Value, &SKI)
    39  			if err != nil {
    40  				return nil, errors.New(fmt.Sprintf("%v failed to unmarshal Subject Key Identifier", err))
    41  			}
    42  
    43  			return SKI, nil
    44  		}
    45  	}
    46  	return nil, errors.New("subjectKeyIdentifier not found in certificate")
    47  }