github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/modules/ssh/key_pair.go (about)

     1  package ssh
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"encoding/pem"
     8  
     9  	"github.com/gruntwork-io/terratest/modules/logger"
    10  	"github.com/gruntwork-io/terratest/modules/testing"
    11  	"golang.org/x/crypto/ssh"
    12  )
    13  
    14  // KeyPair is a public and private key pair that can be used for SSH access.
    15  type KeyPair struct {
    16  	PublicKey  string
    17  	PrivateKey string
    18  }
    19  
    20  // GenerateRSAKeyPair generates an RSA Keypair and return the public and private keys.
    21  func GenerateRSAKeyPair(t testing.TestingT, keySize int) *KeyPair {
    22  	keyPair, err := GenerateRSAKeyPairE(t, keySize)
    23  	if err != nil {
    24  		t.Fatal(err)
    25  	}
    26  	return keyPair
    27  }
    28  
    29  // GenerateRSAKeyPairE generates an RSA Keypair and return the public and private keys.
    30  func GenerateRSAKeyPairE(t testing.TestingT, keySize int) (*KeyPair, error) {
    31  	logger.Logf(t, "Generating new public/private key of size %d", keySize)
    32  
    33  	rsaKeyPair, err := rsa.GenerateKey(rand.Reader, keySize)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	// Extract the private key
    39  	keyPemBlock := &pem.Block{
    40  		Type:  "RSA PRIVATE KEY",
    41  		Bytes: x509.MarshalPKCS1PrivateKey(rsaKeyPair),
    42  	}
    43  
    44  	keyPem := string(pem.EncodeToMemory(keyPemBlock))
    45  
    46  	// Extract the public key
    47  	sshPubKey, err := ssh.NewPublicKey(rsaKeyPair.Public())
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)
    53  	sshPubKeyStr := string(sshPubKeyBytes)
    54  
    55  	// Return
    56  	return &KeyPair{PublicKey: sshPubKeyStr, PrivateKey: keyPem}, nil
    57  }