如何在Go中使用密码创建RSA私钥?
我阅读了crypto包的文档,但无法从中拼凑出解决方案。
发布于 2016-05-19 07:25:15
第一步,生成一个私钥。第二步,将其转换为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
}https://stackoverflow.com/questions/37316370
复制相似问题