~rogpeppe/juju-core/themue-058-debug-log-api

« back to all changes in this revision

Viewing changes to utils/ssh/generate.go

  • Committer: Frank Mueller
  • Date: 2014-01-07 13:59:00 UTC
  • mfrom: (2152.1.32 juju-core)
  • Revision ID: frank.mueller@canonical.com-20140107135900-t3akd2tp3s5fsujf
merged trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2013 Canonical Ltd.
 
2
// Licensed under the AGPLv3, see LICENCE file for details.
 
3
 
 
4
package ssh
 
5
 
 
6
import (
 
7
        "crypto/rand"
 
8
        "crypto/rsa"
 
9
        "crypto/x509"
 
10
        "encoding/pem"
 
11
        "fmt"
 
12
        "strings"
 
13
 
 
14
        "code.google.com/p/go.crypto/ssh"
 
15
)
 
16
 
 
17
// KeyBits is used to determine the number of bits to use for the RSA keys
 
18
// created using the GenerateKey function.
 
19
var KeyBits = 2048
 
20
 
 
21
// GenerateKey makes a 2048 bit RSA no-passphrase SSH capable key.  The bit
 
22
// size is actually controlled by the KeyBits var. The private key returned is
 
23
// encoded to ASCII using the PKCS1 encoding.  The public key is suitable to
 
24
// be added into an authorized_keys file, and has the comment passed in as the
 
25
// comment part of the key.
 
26
func GenerateKey(comment string) (private, public string, err error) {
 
27
        key, err := rsa.GenerateKey(rand.Reader, KeyBits)
 
28
        if err != nil {
 
29
                return "", "", err
 
30
        }
 
31
 
 
32
        identity := pem.EncodeToMemory(
 
33
                &pem.Block{
 
34
                        Type:  "RSA PRIVATE KEY",
 
35
                        Bytes: x509.MarshalPKCS1PrivateKey(key),
 
36
                })
 
37
 
 
38
        signer, err := ssh.ParsePrivateKey(identity)
 
39
        if err != nil {
 
40
                return "", "", fmt.Errorf("failed to load key: %v", err)
 
41
        }
 
42
 
 
43
        auth_key := string(ssh.MarshalAuthorizedKey(signer.PublicKey()))
 
44
        // Strip off the trailing new line so we can add a comment.
 
45
        auth_key = strings.TrimSpace(auth_key)
 
46
        public = fmt.Sprintf("%s %s\n", auth_key, comment)
 
47
 
 
48
        return string(identity), public, nil
 
49
}