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

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

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

回答
編輯回答
入她眼

在加密解密時(shí),確實(shí)可以直接用file_get_contents的方式讀取key

不過(guò)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 就需要傳入資源類(lèi)型的私鑰。

還有就是效率問(wèn)題,如果加密時(shí)每次讀取的文本格式的密鑰,那 OpenSSL 每次還要為你解析一遍密鑰。比較下面的兩個(gè)加密方法就可以看出效率上的差異了。

<?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;

實(shí)驗(yàn)結(jié)果可以發(fā)現(xiàn)方法2要比方法1來(lái)得慢。

2018年8月22日 05:54