Пример #1
0
// MakeSSHKeyPair make a pair of public and private keys for SSH access.
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
// Private Key generated is PEM encoded
// StackOverflow: Greg http://stackoverflow.com/users/328645/greg in
// http://stackoverflow.com/questions/21151714/go-generate-an-ssh-public-key
// No licence added
func makeSSHKeyPair(bits int, pubKeyPath, privateKeyPath string) error {
	if bits < 1024 {
		return errors.New("Reject using too few bits for key")
	}
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	// generate and write private key as PEM
	privateKeyFile, err := os.OpenFile(privateKeyPath, os.O_WRONLY|os.O_CREATE, 0600)
	defer privateKeyFile.Close()
	if err != nil {
		return err
	}
	privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
	if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
		return err
	}

	// generate and write public key
	pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(pub), 0600)
}
Пример #2
0
func CreatePrivateKey(d *schema.ResourceData, meta interface{}) error {
	keyAlgoName := d.Get("algorithm").(string)
	var keyFunc keyAlgo
	var ok bool
	if keyFunc, ok = keyAlgos[keyAlgoName]; !ok {
		return fmt.Errorf("invalid key_algorithm %#v", keyAlgoName)
	}

	key, err := keyFunc(d)
	if err != nil {
		return err
	}

	var keyPemBlock *pem.Block
	switch k := key.(type) {
	case *rsa.PrivateKey:
		keyPemBlock = &pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(k),
		}
	case *ecdsa.PrivateKey:
		keyBytes, err := x509.MarshalECPrivateKey(k)
		if err != nil {
			return fmt.Errorf("error encoding key to PEM: %s", err)
		}
		keyPemBlock = &pem.Block{
			Type:  "EC PRIVATE KEY",
			Bytes: keyBytes,
		}
	default:
		return fmt.Errorf("unsupported private key type")
	}
	keyPem := string(pem.EncodeToMemory(keyPemBlock))

	pubKey := publicKey(key)
	pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)
	if err != nil {
		return fmt.Errorf("failed to marshal public key: %s", err)
	}
	pubKeyPemBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubKeyBytes,
	}

	d.SetId(hashForState(string((pubKeyBytes))))
	d.Set("private_key_pem", keyPem)
	d.Set("public_key_pem", string(pem.EncodeToMemory(pubKeyPemBlock)))

	sshPubKey, err := ssh.NewPublicKey(pubKey)
	if err == nil {
		// Not all EC types can be SSH keys, so we'll produce this only
		// if an appropriate type was selected.
		sshPubKeyBytes := ssh.MarshalAuthorizedKey(sshPubKey)
		d.Set("public_key_openssh", string(sshPubKeyBytes))
	} else {
		d.Set("public_key_openssh", "")
	}

	return nil
}
Пример #3
0
// ParseKey reads the given RSA private key and create a public one for it.
func ParseKey(pem string) (*Key, error) {
	p, err := ioutil.ReadFile(pem)
	if err != nil {
		return nil, err
	}
	key, err := ssh.ParseRawPrivateKey(p)
	if err != nil {
		return nil, err
	}
	rsaKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		return nil, fmt.Errorf("%q is not a RSA key", pem)
	}
	pub, err := ssh.NewPublicKey(&rsaKey.PublicKey)
	if err != nil {
		return nil, err
	}
	// Compute key fingerprint.
	var buf bytes.Buffer
	for _, b := range md5.Sum(pub.Marshal()) {
		fmt.Fprintf(&buf, "%0.2x:", b)
	}
	return &Key{
		Label:       strings.TrimSuffix(filepath.Base(pem), ".pem"),               // trim .pem file extension
		Key:         string(bytes.TrimRight(ssh.MarshalAuthorizedKey(pub), "\n")), // trim newline
		Fingerprint: string(bytes.TrimRight(buf.Bytes(), ":")),                    // trim dangling colon
		Note:        "{}",
		Tags:        make(Tags),
	}, nil
}
Пример #4
0
// GenerateSSHKeyPair generates new key-pair for use with SSH.
func GenerateSSHKeyPair() (*SSHKeyPair, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		return nil, err
	}

	var privBuf bytes.Buffer

	privPEM := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(priv),
	}

	if err := pem.Encode(&privBuf, privPEM); err != nil {
		return nil, err
	}

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return nil, err
	}

	key := &SSHKeyPair{
		Private: bytes.TrimSpace(privBuf.Bytes()),
		Public:  bytes.TrimSpace(ssh.MarshalAuthorizedKey(pub)),
	}

	sum := sha1.Sum(key.Private)
	key.Name = "koding-ssh-keypair-" + hex.EncodeToString(sum[:])

	return key, nil
}
Пример #5
0
// Serialize an RSA public key to disk format, specifically to the
// format used by SSH. Should return nil if the conversion fails.
func RSAPubKeyToDisk(rsaPubKey *rsa.PublicKey) (out []byte, err error) {
	pubKey, err := ssh.NewPublicKey(rsaPubKey)
	if err == nil {
		out = ssh.MarshalAuthorizedKey(pubKey)
	}
	return out, nil
}
func getSshKey(d *schema.ResourceData, path string) (privatekey string, publickey string, err error) {
	pemBytes, err := ioutil.ReadFile(path)

	if err != nil {
		return "", "", err
	}

	block, _ := pem.Decode(pemBytes)

	if block == nil {
		return "", "", errors.New("File " + path + " contains nothing")
	}

	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

	if err != nil {
		return "", "", err
	}

	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(priv),
	}

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return "", "", err
	}
	publickey = string(ssh.MarshalAuthorizedKey(pub))
	privatekey = string(pem.EncodeToMemory(&priv_blk))

	return privatekey, publickey, nil
}
Пример #7
0
func (g GitConfig) HideKey() GitConfig {
	if g.Key == "" {
		return g
	}
	key, err := ssh.ParseRawPrivateKey([]byte(g.Key))
	if err != nil {
		g.Key = secretReplacement
		return g
	}

	privKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		g.Key = secretReplacement
		return g
	}

	pubKey, err := ssh.NewPublicKey(&privKey.PublicKey)
	if err != nil {
		g.Key = secretReplacement
		return g
	}

	g.Key = string(ssh.MarshalAuthorizedKey(pubKey))
	return g
}
Пример #8
0
func (d *SDeployKeys) ExtractPublicKey(privKey *rsa.PrivateKey) (ssh.PublicKey, error) {
	s, err := ssh.NewPublicKey(&privKey.PublicKey)
	if err != nil {
		return nil, errors.New("Invalid RSA public key format derived from private key")
	}
	return s, nil
}
Пример #9
0
func EncodeSSHKey(public *rsa.PublicKey) ([]byte, error) {
	publicKey, err := ssh.NewPublicKey(public)
	if err != nil {
		return nil, err
	}
	return ssh.MarshalAuthorizedKey(publicKey), nil
}
// NewLinuxKVMCoreOSFactory returns a new HostedProgramFactory that can
// create docker containers to wrap programs.
// TODO(kwalsh) fix comment.
func NewLinuxKVMCoreOSHostFactory(sockPath string, cfg *CoreOSLinuxhostConfig) (HostedProgramFactory, error) {

	// Create a key to use to connect to the instance and set up LinuxHost
	// there.
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	sshpk, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		return nil, err
	}
	pkstr := "ssh-rsa " + base64.StdEncoding.EncodeToString(sshpk.Marshal()) + " linux_host"

	sshpriv, err := ssh.NewSignerFromKey(priv)
	if err != nil {
		return nil, err
	}

	return &LinuxKVMCoreOSHostFactory{
		Cfg:        cfg,
		SocketPath: sockPath,
		PublicKey:  pkstr,
		PrivateKey: sshpriv,
	}, nil
}
Пример #11
0
func NewRandomKeyPair() (*KeyPair, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}

	privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privateKeyDer,
	}
	privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock))

	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	if err != nil {
		return nil, err
	}
	pubBytes := ssh.MarshalAuthorizedKey(pub)

	return &KeyPair{
		PublicKey:  string(pubBytes),
		PrivateKey: privateKeyPem,
	}, nil
}
Пример #12
0
func sshkey(bits int) (string, string, string, error) {
	key, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return "", "", "", err
	}

	private := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(key),
		},
	)

	pub := key.Public()
	pubkey, err := ssh.NewPublicKey(pub)
	if err != nil {
		return "", "", "", err
	}
	public := ssh.MarshalAuthorizedKey(pubkey)

	var fp []string
	f := []byte(fmt.Sprintf("%x", md5.Sum(pubkey.Marshal())))
	for i := 0; i < len(f); i += 2 {
		fp = append(fp, string(f[i:i+2]))
	}
	fingerprint := strings.Join(fp, ":")

	return string(private), string(public), string(fingerprint), nil
}
Пример #13
0
func generateSshKeyPair() Keypair {

	priv, err := rsa.GenerateKey(rand.Reader, 2014)
	if err != nil {
		util.Fatalf("Error generating key", err)
	}

	// Get der format. priv_der []byte
	priv_der := x509.MarshalPKCS1PrivateKey(priv)

	// pem.Block
	// blk pem.Block
	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   priv_der,
	}

	// Resultant private key in PEM format.
	// priv_pem string
	priv_pem := string(pem.EncodeToMemory(&priv_blk))

	// Public Key generation
	sshPublicKey, err := ssh.NewPublicKey(&priv.PublicKey)
	pubBytes := ssh.MarshalAuthorizedKey(sshPublicKey)

	return Keypair{
		pub:  []byte(pubBytes),
		priv: []byte(priv_pem),
	}
}
Пример #14
0
// Generate creates public and private key pairs for using as ssh keys uses
// RSA for generating keys
func Generate() (pubKey string, privKey string, err error) {
	// genereate key pair
	privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
	if err != nil {
		return "", "", err
	}

	/// convert to private key block
	privateKeyBlock := pem.Block{
		Type:    privateKeyType,
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(privateKey),
	}

	// convert to public key
	pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
	if err != nil {
		return "", "", err
	}

	// standart github ssh preferences
	pubKey = fmt.Sprintf("ssh-rsa %v", base64.StdEncoding.EncodeToString(pub.Marshal()))
	privKey = string(pem.EncodeToMemory(&privateKeyBlock))

	return pubKey, privKey, nil
}
Пример #15
0
func NewRandomPublicKey(bits int) (ssh.PublicKey, error) {
	key, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, err
	}

	return ssh.NewPublicKey(key.Public())
}
Пример #16
0
// helper function that marshalls an RSA Public Key to an SSH
// .authorized_keys format
func MarshalPublicKey(pubkey *rsa.PublicKey) string {
	pk, err := ssh.NewPublicKey(pubkey)
	if err != nil {
		return ""
	}

	return string(ssh.MarshalAuthorizedKey(pk))
}
Пример #17
0
func GetAuthorizedKey(seed string) ([]byte, error) {
	key := generateKey(seed)
	ssh_key, err := ssh.NewPublicKey(&key.PublicKey)
	if err != nil {
		return nil, err
	}
	return ssh.MarshalAuthorizedKey(ssh_key), nil
}
Пример #18
0
func TestCreateServerWithKeyPair(t *testing.T) {
	client, err := newClient()
	th.AssertNoErr(t, err)

	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	th.AssertNoErr(t, err)
	pubBytes := ssh.MarshalAuthorizedKey(pub)
	pk := string(pubBytes)

	kp, err := keypairs.Create(client, keypairs.CreateOpts{
		Name:      keyName,
		PublicKey: pk,
	}).Extract()
	th.AssertNoErr(t, err)
	t.Logf("Created key pair: %s\n", kp)

	choices, err := ComputeChoicesFromEnv()
	th.AssertNoErr(t, err)

	name := tools.RandomString("Gophercloud-", 8)
	t.Logf("Creating server [%s] with key pair.", name)

	serverCreateOpts := servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
	}

	server, err := servers.Create(client, keypairs.CreateOptsExt{
		serverCreateOpts,
		keyName,
	}).Extract()
	th.AssertNoErr(t, err)
	defer servers.Delete(client, server.ID)
	if err = waitForStatus(client, server, "ACTIVE"); err != nil {
		t.Fatalf("Unable to wait for server: %v", err)
	}

	server, err = servers.Get(client, server.ID).Extract()
	t.Logf("Created server: %+v\n", server)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, server.KeyName, keyName)

	t.Logf("Deleting key pair [%s]...", kp.Name)
	err = keypairs.Delete(client, keyName).ExtractErr()
	th.AssertNoErr(t, err)

	t.Logf("Deleting server [%s]...", name)
}
Пример #19
0
//export c_NewPublicKey
func c_NewPublicKey(key uint64) (uint64, int, *C.char) {
	obj, ok := GetObject(Handle(key))
	if !ok {
		return IH, ErrorCodeNotFound, C.CString(MessageNotFound)
	}
	key_obj := obj.(ssh.PublicKey)
	pkey, err := ssh.NewPublicKey(key_obj)
	if err != nil {
		return IH, ErrorCodeInternal, C.CString(err.Error())
	}
	return uint64(RegisterObject(&pkey)), ErrorCodeSuccess, nil
}
Пример #20
0
func (c *DigitalOceanCluster) fingerprintSSHKey(privateKey *rsa.PrivateKey) (string, error) {
	rsaPubKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
	if err != nil {
		return "", err
	}
	md5Data := md5.Sum(rsaPubKey.Marshal())
	strbytes := make([]string, len(md5Data))
	for i, b := range md5Data {
		strbytes[i] = fmt.Sprintf("%02x", b)
	}
	return strings.Join(strbytes, ":"), nil
}
Пример #21
0
func genPublicKey(c *C) ssh.PublicKey {
	rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
	c.Assert(err, IsNil)
	var pemBuf bytes.Buffer
	pem.Encode(&pemBuf, &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
	})
	rsaPubKey, err := ssh.NewPublicKey(&rsaKey.PublicKey)
	c.Assert(err, IsNil)
	return rsaPubKey
}
Пример #22
0
func (suite *UserTestSuite) TestAddPublicKey() {
	name := "acme.user.add.key"

	// Create Certificate
	crt := suite.generateCertificate()

	// Create user
	user, err := suite.US.Create(name)
	suite.Nil(err)
	suite.NotNil(user)

	// Get key ring
	keyRing := user.KeyRing()
	suite.NotNil(keyRing)

	// Encode cert
	pemFile := new(bytes.Buffer)
	pemkey := &pem.Block{
		Type:  "CERTIFICATE",
		Bytes: crt}
	pem.Encode(pemFile, pemkey)

	// Add key
	fp, err := keyRing.AddPublicKey(pemFile.Bytes())
	suite.Nil(err)

	// Validate key
	suite.KS.ReadTx(func(bkt *bolt.Bucket) {
		userBucket := bkt.Bucket([]byte(name))

		keys := userBucket.Bucket([]byte("keys"))
		suite.NotNil(keys)

		// Pub key
		pub, err := x509.ParseCertificate(crt)
		suite.Nil(err)

		// Convert public key to SSH key format
		sshKey, err := ssh.NewPublicKey(pub.PublicKey)
		suite.Nil(err)

		// Convert key to bytes
		key := sshKey.Marshal()
		fingerprint := auth.CreateFingerprint(key)

		// Get key
		suite.Equal(key, keys.Get([]byte(fingerprint)))

		// Verify fingerprint
		suite.Equal(fingerprint, fp)
	})
}
Пример #23
0
// AddPublicKey simply adds a public key to the user's key ring
func (b *boltKeyRing) AddPublicKey(pemBytes []byte) (fingerprint string, e error) {
	b.users.WriteTx(func(bkt *bolt.Bucket) {
		if len(pemBytes) == 0 {
			e = ErrInvalidCertificate
			return
		}

		// Get user bucket
		user := bkt.Bucket(b.username)

		// If user is nil, the user does not exist
		if user == nil {
			e = ErrUserDoesNotExist
			return
		}

		// Get keys sub-bucket
		keys, err := user.CreateBucketIfNotExists([]byte("keys"))
		if err != nil {
			return
		}

		// Decode PEM bytes
		block, _ := pem.Decode(pemBytes)
		if block == nil {
			e = ErrInvalidCertificate
			return
		}

		pub, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			e = ErrInvalidCertificate
			return
		}

		// Convert Public Key to SSH format
		sshKey, err := ssh.NewPublicKey(pub.PublicKey)
		if err != nil {
			e = ErrFailedKeyConvertion
			return
		}

		// Convert key to bytes
		key := sshKey.Marshal()
		fingerprint = auth.CreateFingerprint(key)

		// Write key to keys bucket
		e = keys.Put([]byte(fingerprint), key)
		return
	})
	return
}
Пример #24
0
func GenerateECDSAKeyPair(keysize int, password string) (public, private []byte, err error) {
	var curve elliptic.Curve
	switch keysize {
	case 256:
		curve = elliptic.P256()
	case 384:
		curve = elliptic.P384()
	case 521:
		curve = elliptic.P521()
	default:
		return
	}

	// Generate the public/private key pair
	prvKey, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err != nil {
		return
	}

	// Marshal the public key
	sshPubKey, err := ssh.NewPublicKey(&prvKey.PublicKey)
	if err != nil {
		return
	}
	public = ssh.MarshalAuthorizedKey(sshPubKey)

	// Marshal the private key
	prvKeyDer, err := x509.MarshalECPrivateKey(prvKey)
	if err != nil {
		return
	}
	block := &pem.Block{Type: "EC PRIVATE KEY", Bytes: prvKeyDer}

	// Encrypt the private key
	if len(password) != 0 {
		// AES-128 is the only option for private key encryption just like in ssh-keygen.
		block, err = x509.EncryptPEMBlock(rand.Reader,
			"EC PRIVATE KEY",
			prvKeyDer,
			[]byte(password),
			x509.PEMCipherAES128)
		if err != nil {
			return
		}
	}

	private = pem.EncodeToMemory(block)
	return
}
Пример #25
0
func newUserKey(pubKeyFile string) (*userKey, error) {
	userKey := new(userKey)
	if len(pubKeyFile) > 0 {
		pubKeyBytes, err := ioutil.ReadFile(pubKeyFile)
		if err != nil {
			return nil, errors.New("Failed to read public key")
		}
		userKey.PublicKey, _, _, _, err = ssh.ParseAuthorizedKey(pubKeyBytes)
		if err != nil {
			return nil, errors.New("Failed to parse authorized key")
		}

		return userKey, nil
	}

	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, errors.New("Failed to generate key pair")
	}
	userKey.PublicKey, err = ssh.NewPublicKey(key.Public())
	if err != nil {
		return nil, errors.New("Failed to extract public key from generated key pair")
	}

	// To support Ansible calling back to us we need to write
	// this file down
	privateKeyDer := x509.MarshalPKCS1PrivateKey(key)
	privateKeyBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privateKeyDer,
	}
	tf, err := ioutil.TempFile("", "ansible-key")
	if err != nil {
		return nil, errors.New("failed to create temp file for generated key")
	}
	_, err = tf.Write(pem.EncodeToMemory(&privateKeyBlock))
	if err != nil {
		return nil, errors.New("failed to write private key to temp file")
	}

	err = tf.Close()
	if err != nil {
		return nil, errors.New("failed to close private key temp file")
	}
	userKey.privKeyFile = tf.Name()

	return userKey, nil
}
Пример #26
0
func sshKey() (pubKey string, auth ssh.AuthMethod, err error) {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return "", nil, err
	}
	signer, err := ssh.NewSignerFromKey(key)
	if err != nil {
		return "", nil, err
	}
	pub, err := ssh.NewPublicKey(&key.PublicKey)
	if err != nil {
		return "", nil, err
	}
	return string(ssh.MarshalAuthorizedKey(pub)), ssh.PublicKeys(signer), nil
}
Пример #27
0
func createKey() (string, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return "", err
	}

	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	if err != nil {
		return "", err
	}

	pubBytes := ssh.MarshalAuthorizedKey(pub)
	pk := string(pubBytes)
	return pk, nil
}
Пример #28
0
func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, keySize)
	if err != nil {
		return nil, err
	}

	publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
	if err != nil {
		return nil, err
	}

	return &OpenSshKeyPair{
		privateKey: privateKey,
		publicKey:  publicKey,
	}, nil
}
// Run executes the Packer build step that generates SSH key pairs.
// The key pairs are added to the multistep state as "ssh_private_key" and
// "ssh_public_key".
func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating temporary SSH key for instance...")
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		err := fmt.Errorf("Error creating temporary ssh key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	priv_blk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(priv),
	}

	pub, err := ssh.NewPublicKey(&priv.PublicKey)
	if err != nil {
		err := fmt.Errorf("Error creating temporary ssh key: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}
	state.Put("ssh_private_key", string(pem.EncodeToMemory(&priv_blk)))
	state.Put("ssh_public_key", string(ssh.MarshalAuthorizedKey(pub)))

	if s.Debug {
		ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath))
		f, err := os.Create(s.DebugKeyPath)
		if err != nil {
			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
			return multistep.ActionHalt
		}

		// Write out the key
		err = pem.Encode(f, &priv_blk)
		f.Close()
		if err != nil {
			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
			return multistep.ActionHalt
		}
	}
	return multistep.ActionContinue
}
Пример #30
0
// Creates a new RSA key pair with the given key length. The private key will be
// of pem format and the public key will be of OpenSSH format.
func generateRSAKeys(keyBits int) (publicKeyRsa string, privateKeyRsa string, err error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, keyBits)
	if err != nil {
		return "", "", fmt.Errorf("error generating RSA key-pair: %s", err)
	}

	privateKeyRsa = string(pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
	}))

	sshPublicKey, err := ssh.NewPublicKey(privateKey.Public())
	if err != nil {
		return "", "", fmt.Errorf("error generating RSA key-pair: %s", err)
	}
	publicKeyRsa = "ssh-rsa " + base64.StdEncoding.EncodeToString(sshPublicKey.Marshal())
	return
}