本文整理汇总了Golang中code/google/com/p/go/crypto/ssh.MarshalAuthorizedKey函数的典型用法代码示例。如果您正苦于以下问题:Golang MarshalAuthorizedKey函数的具体用法?Golang MarshalAuthorizedKey怎么用?Golang MarshalAuthorizedKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MarshalAuthorizedKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestAgentForward
func TestAgentForward(t *testing.T) {
server := newServer(t)
defer server.Shutdown()
conn := server.Dial(clientConfig())
defer conn.Close()
keyring := agent.NewKeyring()
keyring.Add(testPrivateKeys["dsa"], nil, "")
pub := testPublicKeys["dsa"]
sess, err := conn.NewSession()
if err != nil {
t.Fatalf("NewSession: %v", err)
}
if err := agent.RequestAgentForwarding(sess); err != nil {
t.Fatalf("RequestAgentForwarding: %v", err)
}
if err := agent.ForwardToAgent(conn, keyring); err != nil {
t.Fatalf("SetupForwardKeyring: %v", err)
}
out, err := sess.CombinedOutput("ssh-add -L")
if err != nil {
t.Fatalf("running ssh-add: %v, out %s", err, out)
}
key, _, _, _, err := ssh.ParseAuthorizedKey(out)
if err != nil {
t.Fatalf("ParseAuthorizedKey(%q): %v", out, err)
}
if !bytes.Equal(key.Marshal(), pub.Marshal()) {
t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub))
}
}
示例2: CreateSSHKey
// CreateSSHKey is used to generate rsa private & public keys that are used to
// set keys for ssh login to a server.
func CreateSSHKey() (string, string, error) {
pk, e := rsa.GenerateKey(rand.Reader, 2014)
if e != nil {
return "", "", e
}
pkDer := x509.MarshalPKCS1PrivateKey(pk)
pkBlk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: pkDer,
}
pkPem := string(pem.EncodeToMemory(&pkBlk))
pubK := pk.PublicKey
pub, e := ssh.NewPublicKey(&pubK)
if e != nil {
return "", "", e
}
pubBytes := ssh.MarshalAuthorizedKey(pub)
return string(pkPem), string(pubBytes), nil
}
示例3: TestSSHD
func TestSSHD(t *testing.T) {
block, _ := pem.Decode([]byte(testClientPrivateKey))
rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
pub, _ := ssh.NewPublicKey(&rsakey.PublicKey)
cmd, c, err := startSSHD(ssh.MarshalAuthorizedKey(pub))
if err != nil {
t.Fatal(err)
}
defer cmd.Wait()
defer cmd.Process.Kill()
u, err := user.Current()
if err != nil {
t.Fatal(err)
}
_ = u
config := &ssh.ClientConfig{
User: u.Username,
Auth: []ssh.ClientAuth{ssh.ClientAuthKeyring(&keyring{rsakey})},
}
client, err := ssh.Client(c, config)
if err != nil {
t.Fatal(err)
}
sess, err := client.NewSession()
if err != nil {
t.Fatal(err)
}
out, err := sess.Output("echo hello")
if err != nil {
t.Fatal(err)
}
if string(out) != "hello\n" {
t.Fatalf("out = %q want %q", string(out), "hello\n")
}
}
示例4: GenerateKey
func GenerateKey() (pkPem []byte, pubkPem []byte, pubSSHAK []byte, err error) {
pk, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return
}
pkDer := x509.MarshalPKCS1PrivateKey(pk)
pkBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: pkDer,
}
pkPem = pem.EncodeToMemory(&pkBlock)
pubk := pk.PublicKey
pubkDer, err := x509.MarshalPKIXPublicKey(&pubk)
if err != nil {
return
}
pubkBlock := pem.Block{
Type: "PUBLIC KEY",
Headers: nil,
Bytes: pubkDer,
}
pubkPem = pem.EncodeToMemory(&pubkBlock)
pubSSH, err := ssh.NewPublicKey(&pubk)
if err != nil {
return
}
pubSSHAK = ssh.MarshalAuthorizedKey(pubSSH)
return
}
示例5: main
func main() {
log.SetFlags(0)
maybePrintInfo()
maybeProxy()
args := os.Args[1:]
runxURL, err := getToken()
if err != nil {
log.Fatal(err)
}
if len(args) > 0 && args[0] == "-d" {
args = args[1:]
_, err := herokuRun(strings.Join(args, " "), nil)
if err != nil {
log.Fatal(err)
}
return
}
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
log.Fatal("keygen", err)
}
pub, err := ssh.NewPublicKey(&key.PublicKey)
if err != nil {
log.Fatal(err)
}
uuid, err := herokuRun(script, map[string]string{
"RUNX_URL": runxURL,
"AUTHORIZED_KEYS": string(ssh.MarshalAuthorizedKey(pub)),
})
if err != nil {
log.Fatal(err)
}
log.Fatal(execSSH(runxURL, uuid, key, args))
}
示例6: Run
// Run executes the Packer build step that generates SSH key pairs.
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)))
return multistep.ActionContinue
}
示例7: newServer
// newServer returns a new mock ssh server.
func newServer(t *testing.T) *server {
dir, err := ioutil.TempDir("", "sshtest")
if err != nil {
t.Fatal(err)
}
f, err := os.Create(filepath.Join(dir, "sshd_config"))
if err != nil {
t.Fatal(err)
}
err = configTmpl.Execute(f, map[string]string{
"Dir": dir,
})
if err != nil {
t.Fatal(err)
}
f.Close()
for k, v := range testdata.PEMBytes {
filename := "id_" + k
writeFile(filepath.Join(dir, filename), v)
writeFile(filepath.Join(dir, filename+".pub"), ssh.MarshalAuthorizedKey(testPublicKeys[k]))
}
return &server{
t: t,
configfile: f.Name(),
cleanup: func() {
if err := os.RemoveAll(dir); err != nil {
t.Error(err)
}
},
}
}
示例8: handleAuth
// handleAuth checks authentication against etcd using CanConnect and sets the needed
// environment variables for later parts of the builder to use. It takes in the SSH
// connection metadata, the public key of the user, and returns the SSH
// permissions of the connection and an error if they are not authorized.
func handleAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if conn.User() != "git" {
return nil, ErrUnauthorized
}
keydata := string(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key)))
etcd := etcd.NewClient([]string{*etcduplink})
fp := utils.GetFingerprint(keydata)
user, allowed := utils.CanConnect(etcd, keydata)
if allowed {
log.Printf("User %s (%s) accepted with fingerprint %s", user, conn.RemoteAddr().String(), fp)
return &ssh.Permissions{
Extensions: map[string]string{
"environ": fmt.Sprintf("USER=%s\nKEY='%s'\nFINGERPRINT=%s\n", user, keydata, fp),
"user": user,
"fingerprint": fp,
},
}, nil
} else {
log.Printf("Connection from %s rejected (bad key)", conn.RemoteAddr().String())
}
return nil, ErrUnauthorized
}
示例9: pickSSHKey
func pickSSHKey(candidateKeys map[string]string, w io.Writer) (ssh.PublicKey, error) {
i := 0
keyLst := make([]ssh.PublicKey, len(candidateKeys))
for key, comment := range candidateKeys {
pubKey, _, ok := ssh.ParsePublicKey([]byte(key))
if !ok {
continue
}
keyLst[i] = pubKey
k := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pubKey)))
l := fmt.Sprintf("[ %d ] %s...%s %s\n", i+1, k[0:24], k[len(k)-24:], comment)
w.Write([]byte(l))
i += 1
}
if i == 0 {
return nil, errors.New("No ssh keys found.")
}
choice, err := pick("key", i)
if err != nil {
return nil, err
}
return keyLst[choice], nil
}
示例10: marshalPublicKey
// 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))
}
示例11: MarshalPublicKey
// helper function that marshalls an RSA Public Key to an SSH
// .authorized_keys format
func MarshalPublicKey(public *rsa.PublicKey) []byte {
private, err := ssh.NewPublicKey(public)
if err != nil {
return []byte{}
}
return ssh.MarshalAuthorizedKey(private)
}
示例12: marshalKey
// marshalKey returns two byte slices: one represent the private key in the PEM
// format, and the other representing the public key in the authorized_keys
// format.
func marshalKey(keyPair *rsa.PrivateKey) (privateKey []byte, publicKey []byte, err error) {
sshPublicKey, err := ssh.NewPublicKey(&keyPair.PublicKey)
if err != nil {
return nil, nil, err
}
publicKey = ssh.MarshalAuthorizedKey(sshPublicKey)
block := pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(keyPair)}
privateKey = pem.EncodeToMemory(&block)
return privateKey, publicKey, nil
}
示例13: TestCreateServerWithKeyPair
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)
}
示例14: checkAuth
func checkAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
status, err := exitStatus(exec.Command(authChecker[0],
append(authChecker[1:], conn.User(), string(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key))))...).Run())
if err != nil {
return nil, err
}
if status.Status == 0 {
return nil, nil
}
return nil, ErrUnauthorized
}
示例15: GenerateNewPublicKey
func GenerateNewPublicKey() string {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal("Failed to generate new RSA key: ", err)
}
pk, err := ssh.NewPublicKey(&key.PublicKey)
if err != nil {
log.Fatal("Failed to generate public key: ", err)
}
return string(ssh.MarshalAuthorizedKey(pk))
}