我在 Node.js 中生成的私钥在 Go 中不被识别为 PEM 格式

2024年 2月 13日 92.0k 0

我在 node.js 中生成的私钥在 go 中不被识别为 pem 格式

php小编西瓜在最近的开发过程中遇到了一个问题,他发现在使用Node.js生成的私钥在Go中无法被识别为PEM格式。这个问题困扰了他很长时间,他尝试了各种方法来解决这个问题,但都没有成功。在这篇文章中,我们将探讨这个问题的原因以及可能的解决方法,帮助读者解决类似的困扰。

问题内容

我使用加密库和以下代码在 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 中清理解密的数据,但它最终起作用了。

以上就是我在 Node.js 中生成的私钥在 Go 中不被识别为 PEM 格式的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论