猿问

Go - 生成 SSH 公钥

我正在尝试在 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.PublicKey

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


阿晨1998
浏览 255回答 3
3回答

慕哥6287543

如果您正在寻找以包含在 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 encodedfunc 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)}

肥皂起泡泡

以返回字符串: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}
随时随地看视频慕课网APP

相关分类

Go
我要回答