简体   繁体   中英

Get private key from a file with DER format (PKCS8) protected with passwordin PHP

this is a new problem that I have tried to find a solution but without success.

This is my necessity. The users will fill a form with a bunch of data and in the same form will upload 2 files and will type a password for one of these files.

  • One file has the private key in DER format (PKCS8) protected with password (the one that the user will type).

  • The other file has the public key in DER format (PKCS8) without password.

Using the keys in this file a will sign the data the user type in the form and generate/download a xml file with the sign in it.

I know that using openssl this requires to be in format PEM, and using the command

“openssl pkcs8 -inform DER private.key -out private.key.pem -passin pass:password”

I can convert the files to this format. But i have a limitation:

I know that i can convert the DER format to PEM easily with a function (i already did that with the file with the public key) but the problem is with the private key that have a password in it.

For security reasons i can not invoke the exec function to perform this action and i don't want to store the files in pem format for the same reasons.

Is there a way (a php library, code, etc) that I can extract the content of the private key file without using openssl nor saving the new files? I'm trying to use other libraries like Crypt_RSA but i have not found an example of how i can perform that with that library.

Any help will be appreciated.

After so many years, I found myself again with this problem but now I have the answer and is very easy:

$path_key = 'C:/Private.key';
$key_content = file_get_contents($path_key);
$pem_from_key = '-----BEGIN ENCRYPTED PRIVATE KEY-----' . PHP_EOL
        . chunk_split(base64_encode($key_content), 64, PHP_EOL)
        . '-----END ENCRYPTED PRIVATE KEY-----' . PHP_EOL;
$private_key = openssl_pkey_get_private($pem_from_key, 'password');
openssl_private_encrypt($data_to_encrypt, $encrypted_data, $private_key);

The private key is encrypted/protected with a passphrase so, when you transform from der to pem, you have to add in the header and footer the text "ENCRYPTED" or it won't work. If the private key is not encrypted/protected you have to remove the "ENCRYPTED" text in the header and footer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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