RSA in PHP is saved in PEM file and can be read directly. Why use a function like openssl_pkey_get_private to load it?

in terms of private key, the saved pem file is opened with ASC characters. You can use it if you get it directly with file_get_contents, so why use openssl_pkey_get_private to read it into resource-based data?

Mar.02,2021

when encrypting and decrypting, you can read key directly with file_get_contents

however, openssl_pkey_get_private is useful, such as extracting the public key from the private key:

<?php
// 1:
$s = time();
$key = openssl_get_privatekey(file_get_contents('private.key'));
for ($i = 0; $i !== 5000; $iPP) {
    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; $iPP) {
    openssl_private_encrypt('hello world', $encrypted, $key);
}
echo time() - $s . PHP_EOL;

the experimental results show that method 2 is slower than method 1.

Menu