I generated a public and private key in Node.js using the crypto library with the following code.
function generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
cipher: "aes-256-cbc",
passphrase: "",
},
});
// Writing the keys in the following files
fs.writeFileSync("public_key", keyPair.publicKey);
fs.writeFileSync("private_key", keyPair.privateKey);
}
I know that the keys are functioning because I have encrypted and decrypted data using them. But I'm trying to use them in Go, and it is unable to detect the private key as PEM format. However, it does recognize the public key. This is the fragment of my go code:
// Load public key from the "public_key" file generated by Node.js
publicKeyData, err := ioutil.ReadFile("public_key")
if err != nil {
fmt.Println("Error reading the public key file:", err)
return
}
// Load public key in PEM format
block, _ := pem.Decode(publicKeyData)
if block == nil || block.Type != "PUBLIC KEY" {
fmt.Println("The public key file is not in PEM format")
return
}
publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
fmt.Println("Error loading the public key:", err)
return
}
// Successfully loaded the public key in Go
fmt.Println("Public key loaded successfully:", publicKey)
// Load private key from the "private_key" file generated by Node.js
privateKeyData, err := ioutil.ReadFile("private_key")
if err != nil {
fmt.Println("Error reading the private key file:", err)
return
}
// Load private key in PEM format
block, _ = pem.Decode(privateKeyData)
if block == nil || block.Type != "PRIVATE KEY" {
fmt.Println("The private key file is not in PEM format")
return
}
Please, I need help. I don't understand why it reads the public key but not the private key when both are being used to encrypt in my other Node.js programs. It says "The private key file is not in PEM format" but it does not make any sense.
I tryed to generate new keys and the exact same problem persist.
I finnaly solved it generating the keys using OpenSSL library on windows cmd. Then I encrypted and decrypted the data using the OpenSSL generated keys. I had to sanitize the decrypted data in go but it worked at last.