繁体   English   中英

将.key转换为.pem

[英]convert .key to .pem

我需要使用私钥进行加密,并且尝试使用以下代码进行加密:

$content = file_get_contents("file.key");

$plaintext = "14d9df79-8c4c-4380-8444-d31e1fd3f78a";

openssl_private_encrypt($plaintext, $encrypted, $content);

$transfer = base64_encode($encrypted);

echo "text encrypted is:" . $transfer;  //encrypted string

我收到错误消息:openssl_private_encrypt():密钥参数在其中不是有效的私钥

我需要对密钥文件做些什么吗? 它是二进制的。

首先,尝试使用openssl将密钥转换为PEM格式:

openssl rsa -inform der -in file.key -outform pem -out filekey.pem

接下来,使用openssl_pkey_get_private从PEM文件中提取私钥。

$key = openssl_pkey_get_private(file_get_contents("filekey.pem"));

$plaintext = "14d9df79-8c4c-4380-8444-d31e1fd3f78a";

openssl_private_encrypt($plaintext, $encrypted, $key);

$transfer = base64_encode($encrypted);

echo "text encrypted is:" . $transfer;  //encrypted string

我不知道任何使用.key扩展名的x509文件格式。 有pem(这是您需要加载到openssl中的格式),DER(文件可能具有.der,.crt或.cer扩展名)或PKCS#12(.pfx .p12)。 可能是 DER或PKCS#12:

 openssl pkcs12 -in file.key -out file.pem -nodes

...将PKCS#12转换为file.pem,

openssl x509 -inform der -in file.key -out file.pem

...转换DER文件。 如果文件格式错误,他们将报告错误。 OTOH,您可以只使用'file'命令来查找文件类型。 (这是假设您具有Posix / Linux系统-您没有说)。

或者,您也可以问问给它的人哪种格式。

解决了我只是用

openssl pkcs8 .....

命令

希望这对其他人有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM