如何在 Go 中加载和解密证书的加密密钥文件?

dik*_*ant 5 go x509certificate

我有一个证书文件和一个密钥文件,其中密钥文件用密码加密。我试图在加载密钥对之前以编程方式解密密钥文件。

// Key file and cert file path
cf := filepath.Join(certPath, certFile)
kf := filepath.Join(certPath, keyFile)

//Read & decode the encrypted key file with the pass to make tls work
keyIn, err := ioutil.ReadFile(kf)
if err != nil {
    log.Error("Read key error", err)
    return nil, err
}

// Decode and decrypt our PEM block
decodedPEM, _ := pem.Decode([]byte(keyIn))
decrypedPemBlock, err := x509.DecryptPEMBlock(decodedPEM, []byte("somepassword"))
if err != nil {
    log.Error("decrypt key error", err)
    return nil, err
}

// Load our decrypted key pair
crt, err := tls.LoadX509KeyPair(cf, string(decrypedPemBlock))
if err != nil {
    log.Error("load key pair error", err)
    return nil, err
}
Run Code Online (Sandbox Code Playgroud)

原始证书和密钥是使用以下 openssl 参数生成的

openssl req -new -newkey rsa:2048 -x509 -keyout $CA_CERT.key -out $CA_CERT -days $validity -passin "pass:$password" -passout "pass:$password" -subj "/C=$C/ST=$ST/L=$L/O=$O/CN=$CN/emailAddress=$EMAIL"
Run Code Online (Sandbox Code Playgroud)

变量相应地替换为 $password 为“somepassword”

我尝试使用openssl rsa命令行解密密钥,并且使用上面的密码可以正常工作。

然而,在 Go 中,我收到一个错误,tls.LoadX509KeyPair说参数无效。

time="2018-01-17T18:57:40Z" level=error msg="load key pair error: open
Run Code Online (Sandbox Code Playgroud)

我最好的猜测是密钥编码可能会被搞乱,我想知道我的代码是否有问题。

更新:添加了错误消息,似乎tls.LoadX509KeyPair无法理解下面评论指出的格式。