github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/auth/key/gen.go (about)

     1  package key
     2  
     3  import (
     4  	"crypto/rand"
     5  
     6  	"github.com/libp2p/go-libp2p-core/crypto"
     7  	crypto_pb "github.com/libp2p/go-libp2p-core/crypto/pb"
     8  )
     9  
    10  // CryptoGenerator is an interface for generating cryptographic info like
    11  // private keys and peerIDs
    12  // TODO(b5): I've moved this here because the key package should be the source
    13  // of all cryptographic data, but this needs work. I'd like to see it reduced
    14  // to just a `GeneratePrivateKey` function
    15  type CryptoGenerator interface {
    16  	// GeneratePrivateKeyAndPeerID returns a base64 encoded private key, and a
    17  	// peerID
    18  	GeneratePrivateKeyAndPeerID() (string, string)
    19  }
    20  
    21  // cryptoGenerator is a source of cryptographic info for RSA keys
    22  type cryptoGenerator struct {
    23  	algo crypto_pb.KeyType
    24  	bits int
    25  }
    26  
    27  var _ CryptoGenerator = (*cryptoGenerator)(nil)
    28  
    29  // NewCryptoGenerator returns the default source of p2p cryptographic info that
    30  // performs expensive computations like repeated primality testing
    31  func NewCryptoGenerator() CryptoGenerator {
    32  	return &cryptoGenerator{
    33  		algo: crypto.Ed25519,
    34  		bits: 0,
    35  	}
    36  }
    37  
    38  // NewRSACryptoGenerator returns a source of RSA based p2p cryptographic info that
    39  // performs expensive computations like repeated primality testing
    40  func NewRSACryptoGenerator() CryptoGenerator {
    41  	return &cryptoGenerator{
    42  		algo: crypto.RSA,
    43  		bits: 2048,
    44  	}
    45  }
    46  
    47  // GeneratePrivateKeyAndPeerID returns a private key and peerID
    48  func (g cryptoGenerator) GeneratePrivateKeyAndPeerID() (privKey, peerID string) {
    49  	r := rand.Reader
    50  	// Generate a key pair for this host. This is a relatively expensive operation.
    51  	if priv, pub, err := crypto.GenerateKeyPairWithReader(int(g.algo), g.bits, r); err == nil {
    52  		privKey, err = EncodePrivKeyB64(priv)
    53  		if err != nil {
    54  			panic(err)
    55  		}
    56  		// Obtain profile.ID from public key
    57  		if pid, err := IDFromPubKey(pub); err == nil {
    58  			peerID = pid
    59  		}
    60  	}
    61  	return
    62  }