为了账号安全,请及时绑定邮箱和手机立即绑定

Go - 生成 SSH 公钥

Go - 生成 SSH 公钥

Go
阿晨1998 2021-07-09 13:11:53
我正在尝试在 Go 中生成一个用于 SSH 的密钥对。我似乎正在创建一个私钥就好了,尽管我不知道如何以正确的格式生成公钥。这是代码:privateKey, err := rsa.GenerateKey(rand.Reader, 2014)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.PublicKeypublicKeyDer, err := x509.MarshalPKIXPublicKey(&publicKey)if err != nil {    return nil, err}publicKeyBlock := pem.Block{    Type:    "PUBLIC KEY",    Headers: nil,    Bytes:   publicKeyDer,}publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))    fmt.Println(privateKeyPem)    fmt.Println(publicKeyPem)
查看完整描述

3 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

如果您正在寻找以包含在 OpenSSH authorized_key 文件中的格式生成密钥,以下是我最近编写的帮助程序:


// 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

func MakeSSHKeyPair(pubKeyPath, privateKeyPath string) error {

    privateKey, err := rsa.GenerateKey(rand.Reader, 1024)

    if err != nil {

        return err

    }


    // generate and write private key as PEM

    privateKeyFile, err := os.Create(privateKeyPath)

    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), 0655)

}


查看完整回答
反对 回复 2021-07-19
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

以返回字符串:


func MakeSSHKeyPair() (string, string, error) {

    privateKey, err := rsa.GenerateKey(rand.Reader, 1024)

    if err != nil {

        return "", "", err

    }


    // generate and write private key as PEM

    var privKeyBuf strings.Builder


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

    if err := pem.Encode(&privKeyBuf, privateKeyPEM); err != nil {

        return "", "", err

    }


    // generate and write public key

    pub, err := ssh.NewPublicKey(&privateKey.PublicKey)

    if err != nil {

        return "", "", err

    }


    var pubKeyBuf strings.Builder

    pubKeyBuf.Write(ssh.MarshalAuthorizedKey(pub))


    return pubKeyBuf.String(), privKeyBuf.String(), nil

}


查看完整回答
反对 回复 2021-07-19
  • 3 回答
  • 0 关注
  • 254 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信