1 回答
TA贡献1810条经验 获得超4个赞
第一步,生成私钥。第二步,将其转换为 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
}
- 1 回答
- 0 关注
- 270 浏览
添加回答
举报
