PHP equivalent to OpenSSL RSA command - php

How could I remove passphase from RSA private key using PHP
I know that in OpenSSL it is this way:
openssl rsa -in key.key -out key.key
and I am searching equivalent command to this one in PHP.
RSA command requires the pass
OpenSSL> rsa -in key2.key -out key2.key
Enter pass phrase for key2.key:

Using phpseclib, a pure PHP RSA implementation:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setPassword('password');
$rsa->loadKey('...');
$rsa->setPassword();
echo $rsa->getPrivateKey();
?>

This would accomplish the same operation using the openssl extension:
$key = file_get_contents('key2.key');
$password = 'your password or pass phrase';
if (false === ($pkey = openssl_pkey_get_private($key, $password))) {
die(openssl_error_string());
}
openssl_pkey_export($pkey, $out_key);
file_put_contents('key2.key', $out_key);
A concrete example:
$key = <<<EOS
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,775352C44A559B6C
V8EuwC29zy4yuY7Ie+HvyygjKJx4G+VF/SgjjCQR+Q/iLaXcoXhIMBmP9ugQpywu
Tgmg25PruaXl3Mabs2h03aUwLyFEEjcnaVz4IFYGflqDIBbSb/Y4Q9Ef0OjbCwCJ
5pEnD0ATPtb+bptHk7VitvyK9vIN4zrqDeWdpGkqhYZx4SkUDLBhcYYYA3eY8P7y
/yeUmHt2p12W7xF4OWflNj0ot7N2GoofKrAomW0vHVAAlVHj4OVyZYeOEG/8gm2A
a3xo+LS9D2tFJjCtnP5ytczWnsoe18bKlWbjV/IimlkVEqR6jx0jC99eCUHyaSvm
OfU/DHHcooBIJxXB5VfxFbRzjyWYgsAiVf2lThvusRb+j8/Ey28t5CWx8ME2hgmk
hrTPmCFor+Lx/7++cmOFWSNvJU8MrC6jH+q2R3xIPuY=
-----END RSA PRIVATE KEY-----
EOS;
$password = 'superman';
if (false === ($pkey = openssl_pkey_get_private($key, $password))) {
die(openssl_error_string());
}
openssl_pkey_export($pkey, $out_key);
echo $out_key;

Related

openssl_private_decrypt() "RSA_padding_check_PKCS1_type_2:pkcs decoding error"

Problem Statement
I'm trying to decrypt data using private_key from PKCS12 formatted file by openssl_private_decrypt(). However I'm getting empty string in response.
Exception
[
0 => "error:0909006C:PEM routines:get_name:no start line"
1 => "error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error"
2 => "error:04065072:rsa routines:rsa_ossl_private_decrypt:padding check failed"
]
Files & Configuration
$pkcs12 = file_get_contents('/path/server.p12');
openssl_pkcs12_read($pkcs12, $p12, '123456');
if (false === openssl_private_decrypt($encrypted, $decrypted, $p12['pkey'], OPENSSL_PKCS1_PADDING))
{
$e = [];
while ($msg = openssl_error_string())
array_push($e, $msg);
dd($e);
}
Edit 1:
I've run the following command to generate CSR as well as private key for SSL certificates
$ openssl req -new -newkey rsa:2048 -nodes -keyout example.key -out example.csr
example.key (Private key in .key format)
example.csr (CSR)
Got certificate & files from CA.
example.crt
intermediate.crt
example.pem
Run below command to convert private key and certificate into to PKCS12 file.
$ openssl pkcs12 -export -in example.crt -inkey example.key -out example.p12 -certfile intermediate.crt
example.p12
Edit 2:
I've example.key header
"""
-----BEGIN PRIVATE KEY-----\n
aasdasdddddddddddddadsssssssjhjjjjjjjjjj\n
.
.
asddddddddasdkjabshjdhajskdhajgggggggggg\n
TtasdhjaskjZPqD0UcJAcP\n
-----END PRIVATE KEY-----\n
"""
Edit 3:
I've converted private key from .key to .pem using below command but still getting same error.
openssl rsa -in example.key -text > example.key.pem
Edit 4:
After some research I found out that '\n' could be the cause of this error as stated in #derN3rd.
1. Declaring local variable
$pkcs8pem = "-----BEGIN PRIVATE KEY-----
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
.
.
ZZZZZZZZZZZZZZZZZZZZZZZZ
-----END PRIVATE KEY-----";
dd($pkcs8pem);
Output:
"""
-----BEGIN PRIVATE KEY-----\n
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n
.
.
ZZZZZZZZZZZZZZZZZZZZZZZZ\n
-----END PRIVATE KEY-----\n
"""
2. Using str_replace()
$privateKey = $p12['pkey'];
$privateKeyClean = str_replace(array("\r", "\n"), '', $privateKey);
dd($privateKeyClean);
Output:
"-----BEGIN PRIVATE KEY-----
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..ZZZZZZZZZZZZZZZZ-----END PRIVATE KEY-----"

problem with PHP RSA encryption using public key return nothing

I have problem with $public_key in RSA encryption
and i receive empty result no error
I am using phpseclib
Example:
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$plaintext = 'test test';
$public_key = '-----BEGIN CERTIFICATE-----
MIIGQjCCBSqgAwIBAgIQNW5duJ7xtvmwd5qObmTdljANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQG
EwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVt
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRswGQYDVQQDExJDZXJ0dW0gTGV2ZWwgSVYgQ0EwHhcN
MTYwNjE1MDU0MTU4WhcNMTkwNjE1MDU0MTU4WjCBvjELMAkGA1UEBhMCUEwxHjAcBgNVBAoMFU1p
bmlzdGVyc3R3byBGaW5hbnNvdzEjMCEGA1UECwwaRGVwYXJ0YW1lbnQgSW5mb3JtYXR5emFjamkx
ETAPBgNVBAcMCFdhcnN6YXdhMRQwEgYDVQQIDAttYXpvd2llY2tpZTEjMCEGA1UEAwwadGVzdC1l
LWRva3VtZW50eS5tZi5nb3YucGwxHDAaBgkqhkiG9w0BCQEWDWpwa0BtZi5nb3YucGwwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6K/2lXWopQyScTXwXduIfWyk+8ZqrGLhUll1F0J7l
6gfyYx3rLzqAeFIn9tJSS8v1PKj6EQ61lEDZcLcbxsAzK3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todHRwOi8vY3JsLmNlcnR1bS5wbC9sNC5jcmwwGAYDVR0R
BBEwD4ENanBrQG1mLmdvdi5wbDANBgkqhkiG9w0BAQUFAAOCAQEAxno58NJnSvAD3eBWI8D2dVPQ
T8Heqg+dvH1okrrBPLg6OV0E+V/KYzWqFoOAFUsmVBw/B2P17brKecwyYCrHOK0aQsvsIeaABBkx
aMhBjkFVz0R4FJtA1/l3lbVRpSAKRHyqw3P7TOzJuAG+kzNxvs0GYOAMhKvUO/ZvghJsYXM4wQ8F
LTNOyrRwdy0OuV8f5ahHU9zWH7cEiaMsnn9bIE4clkY/kTm8b2nOsoadH83YV0MrmPKRCleLE1QW
7Ytj9b+exAXLoB5D2NJqiLJD+LX8Y7CGMWGGLOPwonN9stRew5pRVPhY4j8RCLn0Cpuay3rBoOWs
9mzRTV3IiZZFbw==
-----END CERTIFICATE-----';
$rsa->loadKey($public_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo $ciphertext = $rsa->encrypt($plaintext);
var_dump($rsa->encrypt($plaintext));
but if I change key to this one:
$rsa->loadKey('-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SdPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----');
than it is working.
What is wrong with first key ?
Thanks for any help
The first key isn't a key - it's an X.509 cert. To encrypt something with the public key contained within an X.509 cert you'd need to use File_X509. Something like this (untested):
<?php
include('File/X509.php');
$x509 = new File_X509();
$x509->loadX509('...');
$rsa = $x509->getPublicKey();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;

SSL: match private key with certificate using PHP (without phpseclib)

I have tried to use this PHP code script to check SSL private key with SSL certificate match or not the result is match every time.
error_reporting(E_ALL & ~E_NOTICE);
if (!extension_loaded('OpenSSL')) {
$this->markTestSkipped("Need OpenSSL extension");
}
$pkey = "-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDvwT54v2kQTRP3
ZnJepfuBgEUfrEqBZ7zLm87s1NHwwJNNbwqGCYTIoCv4xDgRCK7X7NVmMyV2OWIn
...
-----END PRIVATE KEY-----";
$cert = "-----BEGIN CERTIFICATE-----
MIIGRTCCBS2gAwIBAgIQVWcnF+whEw+mvnBlp/JMCzANBgkqhkiG9w0BAQsFADCB
kDELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
...
-----END CERTIFICATE-----";
$check_result = check_pkey_cert_match($pkey, $cert);
if($check_result == true) {
echo "Match";
} else {
echo "Not Match";
}
this function use openssl by shell_exec it can export files server.crt, server.key, server.csr
function check_pkey_cert_match($Private_Key, $Certificate) {
//checks if Private Key match Certificate
$random_blurp = rand(10,99999);
$tmp_dir = "/tmp/";
if(openssl_x509_export_to_file($Certificate, $tmp_dir.$random_blurp.'.server.crt')) {
echo "Export Cert OK = ".$tmp_dir.$random_blurp.".server.crt";
} else {
echo "Export Crt Error";
}
if(openssl_pkey_export_to_file($Private_Key, $tmp_dir.$random_blurp.'.server.key')) {
echo "Export Pkey OK = ".$tmp_dir.$random_blurp.".server.key";
} else {
echo "Export Pkey Error";
}
but when i use this shell_exec for check $pkey_check & $cert_check match or not it still result match every time. Because $pkey_check & $cert_check = null
$pkey_check = shell_exec('openssl pkey -in
'.$tmp_dir.$random_blurp.'.server.key -pubout -outform pem | sha256sum');
$cert_check = shell_exec('openssl x509 -in
'.$tmp_dir.$random_blurp.'.server.crt -pubout -outform pem | sha256sum');
// $csr_check = shell_exec('openssl req -in '.$tmp_dir.$random_blurp.'.server.csr -pubout -outform pem | sha256sum');
//remove those temp files.
unlink($tmp_dir.'server.crt');
unlink($tmp_dir.'server_key');
//unlink($tmp_dir.'server.csr');
//Check for match
if ( $cert_check == $pkey_check ) {
return true;
} else {
return false;
}
Result of above script
Export Cert OK = /tmp/41893.server.crt
Export Pkey OK = /tmp/41893.server.key
cert_check =
pkey_check =
Match
I have try another shell_exec but the same resutl
/*
$pkey_check = shell_exec('openssl rsa -noout -modulus -in server.key | openssl md5');
$cert_check = shell_exec('openssl x509 -noout -modulus -in server.crt | openssl md5');
$csr_check = shell_exec('openssl req -noout -modulus -in server.csr | openssl md5');
*/
/*
$pkey_check = shell_exec('openssl rsa -modulus -in '.$tmp_dir.$random_blurp.'.server.key | openssl md5 2>&1');
$cert_check = shell_exec('openssl x509 -modulus -in '.$tmp_dir.$random_blurp.'.server.crt | openssl md5 2>&1');
$csr_check = shell_exec('openssl req -noout -modulus -in '.$tmp_dir.$random_blurp.'.server.csr | openssl md5 2>&1');
*/
$pkey_check = shell_exec('openssl pkey -in '.$tmp_dir.$random_blurp.'.server.key -pubout -outform pem | sha256sum');
$cert_check = shell_exec('openssl x509 -in '.$tmp_dir.$random_blurp.'.server.crt -pubout -outform pem | sha256sum');
// $csr_check = shell_exec('openssl req -in '.$tmp_dir.$random_blurp.'.server.csr -pubout -outform pem | sha256sum');
(Posted on behalf of the question author).
This simple script use to check private key & certificate match or not.
error_reporting(E_ALL & ~E_NOTICE);
if (!extension_loaded('OpenSSL')) {
$this->markTestSkipped("Need OpenSSL extension");
}
Define $cert and $pkey (or use $_POST[$cert] and $_POST[$pkey] instead)
$pkey = "-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDvwT54v2kQTRP3
ZnJepfuBgEUfrEqBZ7zLm87s1NHwwJNNbwqGCYTIoCv4xDgRCK7X7NVmMyV2OWIn
...
-----END PRIVATE KEY-----";
$cert = "-----BEGIN CERTIFICATE-----
MIIGRTCCBS2gAwIBAgIQVWcnF+whEw+mvnBlp/JMCzANBgkqhkiG9w0BAQsFADCB
kDELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
...
-----END CERTIFICATE-----";
Call function check_pkey_cert_match() and result.
$check_result = check_pkey_cert_match($pkey, $cert);
if($check_result == true) {
echo "Match";
} else {
echo "Not Match";
}
Just use Function openssl_x509_check_private_key()
function check_pkey_cert_match($Private_Key, $Certificate) {
//Check for match
if(openssl_x509_check_private_key ( $Certificate , $Private_Key )) {
return true;
} else {
return false;
}
}

openssl_pkey_get_private returns string ''

Recently I use openssl generate RSA Private Key to encrypted my data.
$private_key = "-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDGCn4a42xSG6Hs0h+BSWG/MQmXOpIqd6ptlfFxMFQeL9bvJ9jR j0842NyaWIAedxQrv/0+XC5pYF8ExrcGXCnWtCpUTK2M6cgkTLgkkptLz5N+z8jd AeSbakKkJuQEgEyKI1cIrjRhz6u6yfjoPKZAmVdlwEDN1u4TweZ1HDDxHQIDAQAB AoGANPgvfI+htGBxsf8NsC3peBLspsdiuvsg2YjGeGjdxukyyurUglCbdvACKUJM mlltSrpiSOCtBUBiicuAvrG9+pdjQb1gPui/xj83ZbNytfG6K8UFk6cokH6fEgON Pd3npWlhXwdrJUxcFLzlJzREq18VyAWwgsbH82//ineOF6ECQQD3HOpE+IQ2JDIL Kxna/rVnW5RSvImddKksC4KLk7IsMFqsfo+e/Vkf3D7vmsMDCXCNpt5+ttLF93lU 3Iz1j/bJAkEAzSnJ4kp9rsvf7X5OqLWOJjR6CDGK3RSwSXeSMoJSIvV6rSXXQryU ltiYct5A5Oi3g49cOYNuYMt1bw3uTEVNtQJBAKqR7e8fr3sDrvtgi99LE4I9h3s4 orDp1uANLdYUY9b2pZANaCtxavR//X08UUGmYWeVeFz06zY05S47cp0J+2kCQEyk CbixHxZHLtWnU3cOq5V2EQgyia9g5SHsuv6HVGuezD8WXb2eeNuI+hofEJrynGtX CJqrkHY0SyA7UgPH9+kCQQDRrxJ4plB0nWqhLpdc3OV74vW0m11LS8+270nMMVN1 IP08iRfF4ASWEXoe5A2LNEP4ydFw68Ve08WaRwSJ65kn -----END RSA PRIVATE KEY-----";
$pi_key = openssl_pkey_get_private($private_key);
var_dump($pikey."\n");
return:
string(1) "
"
I use it at my local wampserver,But I get return data is resource.
string(16) "Resource id #46
"
My openssl version:
OpenSSL is pretty picky when it comes to keys. All that base64-encoded data needs to span multiple lines, each of which is, at most, 64 lines long. I used phpseclib to convert you key and it worked fine for me after the conversion (whereas it didn't before):
<?php
include('Crypt/RSA.php');
$key = '-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDGCn4a42xSG6Hs0h+BSWG/MQmXOpIqd6ptlfFxMFQeL9bvJ9jR j0842NyaWIAedxQrv/0+XC5pYF8ExrcGXCnWtCpUTK2M6cgkTLgkkptLz5N+z8jd AeSbakKkJuQEgEyKI1cIrjRhz6u6yfjoPKZAmVdlwEDN1u4TweZ1HDDxHQIDAQAB AoGANPgvfI+htGBxsf8NsC3peBLspsdiuvsg2YjGeGjdxukyyurUglCbdvACKUJM mlltSrpiSOCtBUBiicuAvrG9+pdjQb1gPui/xj83ZbNytfG6K8UFk6cokH6fEgON Pd3npWlhXwdrJUxcFLzlJzREq18VyAWwgsbH82//ineOF6ECQQD3HOpE+IQ2JDIL Kxna/rVnW5RSvImddKksC4KLk7IsMFqsfo+e/Vkf3D7vmsMDCXCNpt5+ttLF93lU 3Iz1j/bJAkEAzSnJ4kp9rsvf7X5OqLWOJjR6CDGK3RSwSXeSMoJSIvV6rSXXQryU ltiYct5A5Oi3g49cOYNuYMt1bw3uTEVNtQJBAKqR7e8fr3sDrvtgi99LE4I9h3s4 orDp1uANLdYUY9b2pZANaCtxavR//X08UUGmYWeVeFz06zY05S47cp0J+2kCQEyk CbixHxZHLtWnU3cOq5V2EQgyia9g5SHsuv6HVGuezD8WXb2eeNuI+hofEJrynGtX CJqrkHY0SyA7UgPH9+kCQQDRrxJ4plB0nWqhLpdc3OV74vW0m11LS8+270nMMVN1 IP08iRfF4ASWEXoe5A2LNEP4ydFw68Ve08WaRwSJ65kn -----END RSA PRIVATE KEY-----';
$pi_key = openssl_pkey_get_private($key);
var_dump($pi_key);
echo "\r\n";
$rsa = new Crypt_RSA();
$rsa->loadKey($key);
$pi_key = openssl_pkey_get_private($rsa);
var_dump($pi_key);
echo "\r\n";
The first one output bool(false) and the second one returned resource(8) of type (OpenSSL key).

openssl: how can i get public key from modulus

I generate a pair of keys using openssl:
shell> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/mike/.ssh/id_rsa): /path/to/test_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /path/to/test_rsa.
Your public key has been saved in /path/to/test_rsa.pub.
And then, I generate modulus from private key:
shell> openssl rsa -in /path/to/test_rsa -noout -modulus > /path/to/modulus.txt
Now, is there any way to get test_rsa.pub(public key) just from modulus?
You can get the public key in a more standardized format using phpseclib, a pure PHP RSA implementation. eg.
<?php
include('Crypt/RSA.php');
$modulus = 'yEQs2LxSHBZgZCH0rRQQy9kmry8g2tNhQL1B9f5azNz9Ce9pXPgSRjVUo1B9Ggb/FK3jy41wWd2IfS6rse3vBzRsabMj29CVODM/19yZPmwEmjJHCgYd+AA2qweKZanDp4FLsSw/kyV5WoPN16GHEMLmLGkJFNIWtzzH5jV+S80=';
$exponent = 'AQAB';
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64_decode($modulus), 256);
$exponent = new Math_BigInteger(base64_decode($exponent), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
echo $rsa->getPublicKey();

Categories