• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ssh.MarshalAuthorizedKey函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/crypto/ssh.MarshalAuthorizedKey函数的典型用法代码示例。如果您正苦于以下问题:Golang MarshalAuthorizedKey函数的具体用法?Golang MarshalAuthorizedKey怎么用?Golang MarshalAuthorizedKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了MarshalAuthorizedKey函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
	}
}
开发者ID:CodeJuan,项目名称:deis,代码行数:34,代码来源:agent_unix_test.go


示例2: theseTwoPublicKeysAreEqual

func theseTwoPublicKeysAreEqual(one, other ssh.PublicKey) bool {
	oneKeyMshld := ssh.MarshalAuthorizedKey(one)
	otherKeyMshld := ssh.MarshalAuthorizedKey(other)
	if len(oneKeyMshld) != len(otherKeyMshld) {
		return false
	}
	for i, elm := range oneKeyMshld {
		if elm != otherKeyMshld[i] {
			return false
		}
	}
	return true
}
开发者ID:nsimaria,项目名称:sectra,代码行数:13,代码来源:main.go


示例3: GenerateSSHKeyPair

// 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
}
开发者ID:koding,项目名称:koding,代码行数:33,代码来源:stackmethods.go


示例4: ParseKey

// 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
}
开发者ID:koding,项目名称:koding,代码行数:31,代码来源:keys.go


示例5: HideKey

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
}
开发者ID:weaveworks,项目名称:flux,代码行数:25,代码来源:config.go


示例6: handleAuth

func handleAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
	if *authHook == "" {
		// allow all
		return &ssh.Permissions{
			Extensions: map[string]string{
				"user": conn.User(),
			},
		}, nil
	}

	keydata := string(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key)))
	cmd, err := handlerCmd(*authHook, conn.User(), keydata)
	if err != nil {
		return nil, err
	}
	var output bytes.Buffer
	cmd.Stdout = &output
	cmd.Stderr = &output
	status, err := exitStatus(cmd.Run())
	if err != nil {
		return nil, err
	}
	if status.Status == 0 {
		return &ssh.Permissions{
			Extensions: map[string]string{
				"environ": strings.Trim(output.String(), "\n"),
				"user":    conn.User(),
			},
		}, nil
	}
	debug("authentication hook status:", status.Status)
	return nil, fmt.Errorf("authentication failed")
}
开发者ID:simudream,项目名称:sshfront,代码行数:33,代码来源:handlers.go


示例7: generateSshKeyPair

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),
	}
}
开发者ID:MarWestermann,项目名称:gofabric8,代码行数:31,代码来源:secrets.go


示例8: EncodeSSHKey

func EncodeSSHKey(public *rsa.PublicKey) ([]byte, error) {
	publicKey, err := ssh.NewPublicKey(public)
	if err != nil {
		return nil, err
	}
	return ssh.MarshalAuthorizedKey(publicKey), nil
}
开发者ID:nirdothan,项目名称:kubernetes,代码行数:7,代码来源:ssh.go


示例9: CmdAdd

func CmdAdd(name, keyPath, svcName string, id IDeployKeys, is services.IServices) error {
	if strings.ContainsAny(name, config.InvalidChars) {
		return fmt.Errorf("Invalid SSH key name. Names must not contain the following characters: %s", config.InvalidChars)
	}
	if _, err := os.Stat(keyPath); os.IsNotExist(err) {
		return fmt.Errorf("A file does not exist at path '%s'", keyPath)
	}
	service, err := is.RetrieveByLabel(svcName)
	if err != nil {
		return err
	}
	if service == nil {
		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", svcName)
	}
	if service.Type != "code" {
		return fmt.Errorf("You can only add deploy keys to code services, not %s services", service.Type)
	}
	key, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return err
	}
	k, err := id.ParsePublicKey(key)
	if err != nil {
		return err
	}
	key = ssh.MarshalAuthorizedKey(k)
	return id.Add(name, "ssh", string(key), service.ID)
}
开发者ID:catalyzeio,项目名称:cli,代码行数:28,代码来源:add.go


示例10: sshkey

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
}
开发者ID:starkandwayne,项目名称:safe,代码行数:29,代码来源:ssh.go


示例11: CreatePrivateKey

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
}
开发者ID:RezaDKhan,项目名称:terraform,代码行数:60,代码来源:resource_private_key.go


示例12: getSshKey

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
}
开发者ID:hashicorp,项目名称:terraform,代码行数:34,代码来源:resource_profitbricks_server.go


示例13: RSAPubKeyToDisk

// 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
}
开发者ID:jddixon,项目名称:xlCrypto_go,代码行数:9,代码来源:rsa_serialization.go


示例14: NewRandomKeyPair

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
}
开发者ID:brkt,项目名称:packer,代码行数:26,代码来源:keypair.go


示例15: makeSSHKeyPair

// 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)
}
开发者ID:dedis,项目名称:cothority,代码行数:33,代码来源:lib.go


示例16: Listen

// Listen starts a SSH server listens on given port.
func Listen(port int) {
	config := &ssh.ServerConfig{
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
			if err != nil {
				log.Error(3, "SearchPublicKeyByContent: %v", err)
				return nil, err
			}
			return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
		},
	}

	keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
	if !com.IsExist(keyPath) {
		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
		_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
		if err != nil {
			panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
		}
		log.Trace("New private key is generateed: %s", keyPath)
	}

	privateBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic("Fail to load private key")
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Fail to parse private key")
	}
	config.AddHostKey(private)

	go listen(config, port)
}
开发者ID:cuteluo1983,项目名称:gogs,代码行数:35,代码来源:ssh.go


示例17: keyAlert

func keyAlert(metadata ssh.ConnMetadata, key ssh.PublicKey) string {
	meta := baseAlertMap(metadata)
	meta["authtype"] = "publickey"
	meta["key"] = string(ssh.MarshalAuthorizedKey(key))

	return alert.NewSplunkAlertMessage(meta)
}
开发者ID:Senior-Design-May1601,项目名称:fssh,代码行数:7,代码来源:main.go


示例18: TestPatterns

func (S) TestPatterns(c *C) {
	const sep = " "
	var input bytes.Buffer

	key := genPublicKey(c)
	keyBytes := bytes.TrimRight(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key)), "\n")

	// format: pattern
	input.WriteString("*.example")
	input.WriteString(sep)
	input.Write(keyBytes)
	input.WriteString("\n")

	// format: negated pattern
	input.WriteString("!*.example.or?")
	input.WriteString(sep)
	input.Write(keyBytes)
	input.WriteString("\n")

	k, err := Unmarshal(bytes.NewReader(input.Bytes()))
	c.Assert(err, IsNil)

	// Test HostKeyCallback
	addr := &net.TCPAddr{
		Port: 22,
	}
	c.Assert(k.HostKeyCallback("foo.example:22", addr, key), IsNil)                         // pattern match
	c.Assert(k.HostKeyCallback("foo.example.org:22", addr, key), Equals, HostNotFoundError) // negated pattern match
	c.Assert(k.HostKeyCallback("anything.example.com:22", addr, key), IsNil)                // negated pattern miss

	// Make sure output is the same as input
	var output bytes.Buffer
	c.Assert(k.Marshal(&output), IsNil)
	c.Assert(output.String(), Equals, input.String())
}
开发者ID:ably-forks,项目名称:flynn,代码行数:35,代码来源:knownhosts_test.go


示例19: 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))
}
开发者ID:Clever,项目名称:drone,代码行数:10,代码来源:sshutil.go


示例20: uploadPublicKey

func uploadPublicKey(client *godo.Client, publicKey ssh.PublicKey, id string) (*godo.Key, error) {
	createRequest := &godo.KeyCreateRequest{
		Name:      keyBaseName + id,
		PublicKey: string(ssh.MarshalAuthorizedKey(publicKey)),
	}
	key, _, err := client.Keys.Create(createRequest)
	return key, err
}
开发者ID:xperimental,项目名称:yovpn,代码行数:8,代码来源:key.go



注:本文中的golang.org/x/crypto/ssh.MarshalAuthorizedKey函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ssh.NewClient函数代码示例发布时间:2022-05-28
下一篇:
Golang ssh.Marshal函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap