Hey everyone.
I’m using the x509 package and I’m trying to parse the private key stored in my .env file using the x509.ParsePKCS8PrivateKey method.
The method throws the following error: “asn1: structure error: tags don’t match (2 vs {class:0 tag:16 length:95 isCompound:true}) {optional:false explicit:false application:false private:false defaultValue: tag: stringType:0 timeType:0 set:false omitEmpty:false} int @2”.
I asume that the error is caused due to the format of the private key in the .env file and the fact that a passphrase was used to generated. (I used the openssl command).
The format of the private key the .env file is the following
PRIVATE_KEY="-----BEGIN ENCRYPTED PRIVATE KEY-----
blablablabla
-----END ENCRYPTED PRIVATE KEY-----
"
Here’s is my code
privateKeyPEM := os.Getenv("PRIVATE_KEY")
// get private key from .env file
block, _ := pem.Decode([]byte(privateKeyPEM))
if block == nil {
http.Error(w, "{\"error\": \"Error decoding private key\"}", http.StatusBadRequest)
return
}
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
fmt.Println(err.Error())
http.Error(w, "{\"error\": \"Error parsing private key\"}", http.StatusBadRequest)
return
}
The goal of this code is to use the private key inside an http handler in order to decrypt some data coming from the client. After I receive the data I call the rsa.DecryptPKCS1v15(rand.Reader, privateKey, ecryptedData)
to decrypt the data, but the code never reaches this point.
Any ideas would be appreciated. My Go version is 1.21
Thank you in advance