Skip to content

Commit

Permalink
[FAB-7674] use buffers instead of temporary files
Browse files Browse the repository at this point in the history
GenerateCertificatesOrPanic was using temporary files when a simple
buffer is sufficient. This resulted in untracked files getting left
behind when tests failed.

Change-Id: I2bdcafde387509a00563315ddd11eccbb7e95584
Signed-off-by: Matthew Sykes <sykesmat@us.ibm.com>
  • Loading branch information
sykesm committed Jan 9, 2018
1 parent 3178dbf commit 78373e9
Showing 1 changed file with 3 additions and 27 deletions.
30 changes: 3 additions & 27 deletions gossip/comm/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,39 +13,21 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"math/big"
"os"

"github.com/hyperledger/fabric/common/util"
gutil "github.com/hyperledger/fabric/gossip/util"
"golang.org/x/net/context"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
)

func writeFile(filename string, keyType string, data []byte) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return pem.Encode(f, &pem.Block{Type: keyType, Bytes: data})
}

// GenerateCertificatesOrPanic generates a a random pair of public and private keys
// and return TLS certificate
func GenerateCertificatesOrPanic() tls.Certificate {
privKeyFile := fmt.Sprintf("key.%d.priv", gutil.RandomUInt64())
certKeyFile := fmt.Sprintf("cert.%d.pub", gutil.RandomUInt64())

defer os.Remove(privKeyFile)
defer os.Remove(certKeyFile)
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
panic(err)
}

sn, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
panic(err)
Expand All @@ -59,19 +41,13 @@ func GenerateCertificatesOrPanic() tls.Certificate {
if err != nil {
panic(err)
}
err = writeFile(certKeyFile, "CERTIFICATE", rawBytes)
if err != nil {
panic(err)
}
privBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
panic(err)
}
err = writeFile(privKeyFile, "EC PRIVATE KEY", privBytes)
if err != nil {
panic(err)
}
cert, err := tls.LoadX509KeyPair(certKeyFile, privKeyFile)
encodedCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rawBytes})
encodedKey := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes})
cert, err := tls.X509KeyPair(encodedCert, encodedKey)
if err != nil {
panic(err)
}
Expand Down

0 comments on commit 78373e9

Please sign in to comment.