github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/orderer/mocks/util/util.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package util
     8  
     9  import (
    10  	"crypto/rand"
    11  	"crypto/rsa"
    12  	"crypto/x509"
    13  	"crypto/x509/pkix"
    14  	"encoding/pem"
    15  	"math/big"
    16  )
    17  
    18  // GenerateMockPublicPrivateKeyPairPEM returns public/private key pair encoded
    19  // as PEM strings.
    20  func GenerateMockPublicPrivateKeyPairPEM(isCA bool) (string, string, error) {
    21  	privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
    22  	if err != nil {
    23  		return "", "", err
    24  	}
    25  	privateKeyPEM := string(pem.EncodeToMemory(
    26  		&pem.Block{
    27  			Type:  "RSA PRIVATE KEY",
    28  			Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
    29  		},
    30  	))
    31  
    32  	template := x509.Certificate{
    33  		SerialNumber: big.NewInt(100),
    34  		Subject: pkix.Name{
    35  			Organization: []string{"Hyperledger Fabric"},
    36  		},
    37  	}
    38  	if isCA {
    39  		template.IsCA = true
    40  		template.KeyUsage |= x509.KeyUsageCertSign
    41  	}
    42  
    43  	publicKeyCert, err := x509.CreateCertificate(rand.Reader, &template, &template, privateKey.Public(), privateKey)
    44  	if err != nil {
    45  		return "", "", err
    46  	}
    47  
    48  	publicKeyCertPEM := string(pem.EncodeToMemory(
    49  		&pem.Block{
    50  			Type:  "CERTIFICATE",
    51  			Bytes: publicKeyCert,
    52  		},
    53  	))
    54  
    55  	return publicKeyCertPEM, privateKeyPEM, nil
    56  }