我使用加密库和以下代码在 Node.js 中生成了公钥和私钥。
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);
}
我知道密钥正在起作用,因为我已经使用它们加密和解密了数据。但我尝试在 Go 中使用它们,它无法检测 PEM 格式的私钥。然而,它确实识别公钥。这是我的 go 代码片段:
// 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
}
拜托,我需要帮助。我不明白为什么当我的其他 Node.js 程序中使用公钥和私钥进行加密时,它会读取公钥而不是私钥。它说“私钥文件不是 PEM 格式”,但这没有任何意义。
我尝试生成新密钥,但完全相同的问题仍然存在。
我最终解决了这个问题,在 Windows cmd 上使用 OpenSSL 库生成密钥。然后我使用 OpenSSL 生成的密钥对数据进行加密和解密。我必须在 go 中清理解密的数据,但它最终起作用了。