如何在 Go 中使用密码创建 RSA 私钥?

How to create RSA private key with passphrase in Go?

如何在 Go 中使用密码创建 RSA 私钥?

我阅读了 crypto 包的文档,但无法从中拼凑出解决方案。

第一步,生成私钥。 第二步,将其转换为PEM格式。第三步,加密PEM。

使用Golang的标准库都可以搞定,非常完善。代码并不难,所以我把它放在这里。所要做的就是知道要使用哪些功能。

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
)

func PrivateKeyToEncryptedPEM(bits int, pwd string) ([]byte, error) {
    // Generate the key of length bits
    key, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        return nil, err
    }

    // Convert it to pem
    block := &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: x509.MarshalPKCS1PrivateKey(key),
    }

    // Encrypt the pem
    if pwd != "" {
        block, err = x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, []byte(pwd), x509.PEMCipherAES256)
        if err != nil {
            return nil, err
        }
    }

    return pem.EncodeToMemory(block), nil
}