鍍金池/ 問答/PHP  網(wǎng)絡安全/ PHP中RSA保存在PEM文件中,直接讀取就可以用,為什么要用openssl_p

PHP中RSA保存在PEM文件中,直接讀取就可以用,為什么要用openssl_pkey_get_private這樣的函數(shù)來加載?

以私鑰來說,存的pem文件,打開就是ASC碼的字符。直接file_get_contents得到就可以用了,為什么要用openssl_pkey_get_private來讀成資源型的數(shù)據(jù)呢?

回答
編輯回答
入她眼

在加密解密時,確實可以直接用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;

實驗結果可以發(fā)現(xiàn)方法2要比方法1來得慢。

2018年8月22日 05:54