PHP中RSA保存在PEM文件中,直接读取就可以用,为什么要用openssl_pkey_get_private这样的函数来加载?

以私钥来说,存的pem文件,打开就是ASC码的字符。直接file_get_contents得到就可以用了,为什么要用openssl_pkey_get_private来读成资源型的数据呢?

阅读 7.9k
1 个回答

在加密解密时,确实可以直接用file_get_contents的方式读取key

不过openssl_pkey_get_private还是有用的,比如从私钥中提取公钥:

<?php
$privateKey = openssl_get_privatekey('private.key');
$detail = openssl_pkey_get_details($privateKey);
$publicKeyString = $detail['key'];
echo $publicKeyString;

其中的 openssl_pkey_get_details 就需要传入资源类型的私钥。

还有就是效率问题,如果加密时每次读取的文本格式的密钥,那 OpenSSL 每次还要为你解析一遍密钥。比较下面的两个加密方法就可以看出效率上的差异了。

<?php
// 方法1:读取密钥到资源
$s = time();
$key = openssl_get_privatekey(file_get_contents('private.key'));
for ($i = 0; $i !== 5000; $i++) {
    openssl_private_encrypt('hello world', $encrypted, $key);
}
echo time() - $s . PHP_EOL;

// 方法2:每次加密直接读取文本
$s = time();
$key = file_get_contents('private.key');
for ($i = 0; $i !== 5000; $i++) {
    openssl_private_encrypt('hello world', $encrypted, $key);
}
echo time() - $s . PHP_EOL;

实验结果可以发现方法2要比方法1来得慢。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题