如何在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
}