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

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

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-----"

How to digitally Sign data using p8 form private key in PHP and Verify it using Public key

I created a P8 format Private Key and signed data Using Java and tried to verify it using Public Key in PHP which Failed.
I created p8 file using openssl command
openssl pkcs8 -topk8 -inform PEM -outform DER -in myprivate.in.key -out myprivate.in.key.p8 -nocrypt
and Signed a Json data using
public byte[] sign(String data, String privateKeyFilePath) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, SignatureException {
byte[] returnVal = null;
Signature signature = Signature.getInstance(RSA_SHA_256);
PrivateKey privateKey = getPrivateKey(privateKeyFilePath);
signature.initSign(privateKey);
signature.update(data.getBytes());
returnVal = signature.sign();
return returnVal;
}
But When I tried to verify it using Public cerificate in PHP using openssl command, it failed
$cert_path = file_get_contents(storage_path('certificates/my_in.cer'));
$pub_key = openssl_get_publickey($cert_path);
$keyData = openssl_pkey_get_details($pub_key);
$pub_key = $keyData['key'];
// $verify = openssl_x509_verify()
$verify = openssl_verify($dataSigned, $signatureDecoded, $pub_key, 'sha256WithRSAEncryption');
What am I doing wrong, Also is there a way I can Sign the data using p8 key in php!
By following this process everything is ok. Maybe it will be useful to you?
Use openssl to generate keys:
# Generate PK
openssl genpkey -algorithm RSA \
-pkeyopt rsa_keygen_bits:2048 \
-pkeyopt rsa_keygen_pubexp:65537 | \
openssl pkcs8 -topk8 -nocrypt -outform der > rsa-2048-private-key.p8
# Convert your PKCS#8 file to a plain private key
openssl pkcs8 -nocrypt -in rsa-2048-private-key.p8 -inform DER -out rsa-2048-private-key.pem
# Generate pub key
openssl rsa -in rsa-2048-private-key.pem -pubout -out rsa-2048-public-key.pem
Test pkey and sign data (index.php):
<?php
$privateKeyFile="file://".__DIR__.DIRECTORY_SEPARATOR."rsa-2048-private-key.pem";
$publicKeyFile="file://".__DIR__.DIRECTORY_SEPARATOR."rsa-2048-public-key.pem";
// Data to sign
$data = 'Hello world!';
// Test on get private key
$pkeyid = openssl_pkey_get_private($privateKeyFile);
if ($pkeyid === false) {
var_dump(openssl_error_string());
}else{
var_dump($pkeyid);
}
// Sign data
openssl_sign($data, $signature, $pkeyid);
// Free memory
openssl_free_key($pkeyid);
// Read pub key
$pubkeyid = openssl_pkey_get_public($publicKeyFile);
// Test if sign is ok
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
echo "Sign OK";
} elseif ($ok == 0) {
echo "Sign NOK";
} else {
echo "Sign check error";
}
// Free memory
openssl_free_key($pubkeyid);
php -S localhost:8000, http://localhost:8000, returns:
resource(2) of type (OpenSSL key) Sign OK

Sign .mobileconfig on a PHP server

Could anyone please tell me how to use openssl smime -sign -signer cert.pem -inkey key.pem -certfile ca-bundle.pem -nodetach -outform der -in profile-uns.mobileconfig -out profile-sig.mobileconfig this within PHP (this one worked properly!)?
I tried
$path = __DIR__ . DIRECTORY_SEPARATOR; // my actual directory
$infilename = $path . 'profile.mobileconfig'; // my unsigned profile
$outfilename = $path . 'profile-sig.mobileconfig'; // my signed profile
$signcert = file_get_contents($path . 'cert.pem'); // my certificate to sign
$privkey = file_get_contents($path . 'key.pem'); // my private key of the certificate
$extracerts = $path . 'ca-bundle.pem'; // the cert chain of my CA
echo openssl_pkcs7_sign($infilename, $outfilename , $signcert, $privkey, array(), PKCS7_NOATTR,$extracerts);
without success. I also tried all of the PKCS7 attributes...
Calling openssl smime with exec works fine:
exec('openssl smime -sign -signer cert.pem -inkey key.pem -certfile ca-bundle.pem -nodetach -outform der -in profile.mobileconfig -out profile-sig.mobileconfig');
Actually, there's an easy approach to solve this problem:
/**
* Sign MobileConfig
*
* #string $file_full_pathname e.g. /tmp/example.mobileconfig
* #string $certificate_pathname e.g. /etc/cert.d/apple_distribution.cert.pem
* #string $private_key_pathname e.g. /etc/cert.d/apple_distribution.key.pem
* #bool $remove_file Optional, default is true, if you want to keep your file then set to false.
*
* #return string
*/
function signMobileConfig (
string $file_full_pathname,
string $certificate_pathname,
string $private_key_pathname,
bool $remove_file = true
) {
openssl_pkcs7_sign(
$file_full_pathname,
$file_full_pathname.'.sig',
file_get_contents($certificate_pathname),
file_get_contents($private_key_pathname),
[], 0
);
$signed = file_get_contents($file_full_pathname.'.sig');
if ($remove_file) {
unlink($file_full_pathname.'.sig');
unlink($file_full_pathname);
}
$trimmed = preg_replace('/(.+\n)+\n/', '', $signed, 1);
return base64_decode($trimmed);
}
Feel free to modify the code above to fulfill your demands.

Decrypt PHP openssl_seal in BASH

I am trying to decrypt some data encrypted via PHP openssl_seal. There don't seem to be any examples involving bash on the net (spent a while researching the matter), so I think this post will help others down the road as well.
As I understand it, I have to first decrypt the key used for RC4 encryption of the actual data using my private key. The data itself, as well as the RC4 key are stored in base64 format.
Data:
Y3jrrTI96HVK7aMR/LrLnCGsqlQNvpQN8TTEoClak2GHk1MMV5/Ig6CD5EuojJaI
gey79XGjf8S9IqLsJ/MxOjODSFM48D+G0lbBW9GEOUFB027pfuHDhyMoTsxjEFBG
XIz5
Envkey:
JJXy5kX9RNSd90BgRSKUX1AGZhwbzetVHKAZTv1/HCBEPGqaGvoWdxaiA8UaJAAr
mS7Sh3pbMm1GN41BYi2r4m9VONknIqn3VB+cikA7ZRxmKOVhRuJTgdjWhrCMyxls
1osAsC8lIFkLo13Z1v8IZAXKGIdyO86WHXzfQku8HAE=
Test private key (this one is crypted, non crypted added at very bottom of a question):
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,CBBD77CC40F395BB
/OwGFHzIoLt4bNFMgdLp25igC8ghJhkRNghg1xpvpZISoniOC2b4oHXOJ4wvt0bj
5Giywp1iQCZUkM7qssJAFcLyTg/ycYz9WuOR5Z68h5p+lz4LnUtcCve2N/goJkwT
r5P59MybJEef27PAQYZyjiDK3eyYJRhcORzd592d81GsXoflroVzK9/eYS33IEeV
Y0grtBoOmDe4eVjDoluZXTGNu2si7SCXs6775jrDpPNMTeYLGApRacJ3TDYHyh9+
dmbaa65ARzRmWtdvvi2zoN/23oie5HUcBgRvubWM4u6LJ4HTLuAjGicpZjIlWQTe
Jex77StHO0zceic++Z9VQ+XfL4zdOHFCJpihunCU+zabqsFNZWZ44LeRul65iNIT
+3XHXezDsvuGkr5aJVvAdp1MxGIf5mO88Ga4pa0qIKFw/sLux+Otx94H45Zb1TgS
At8BU4zK0gSvAU7ea7H/Genug847vh2Up49h8ikmfdiexqnkxDO4N4GLrlDg5yYe
+YLEJyEDYa9Cg9vDV+no6oG1jC+4Fk1s9uk5uDSf4uNN5E5EsxsHS4JxvZ4xnWI7
DYbsy8XOwrrIptJvlttVNIYuobwFfDoWlf9yiAtsIKIVHhhVMgMSWc/0jPEKRmmv
NKMy6sGTEj6LGqh6R7bpeS3joccA8oAi0PjLil1Lt/bLBVAJ1JemLDCfJxjHqCmv
VfBcmF1YqxPKQl9cacUmZhozij1qDTghqIxpdQ/Y+HywGyfJtraDlYkGJ+UFgzh9
NEl1gebVhVBATrNodbUEfzJRz04/1BR2I1WPVcC93lo=
-----END RSA PRIVATE KEY-----
So I'm doing:
Decode from base64 (have tried getting data without base64, still the same result/using base64 to ensure there are no issues with encoding etc.):
base64 --decode envkey > envun
Decrypting the envkey with my private key:
openssl rsautl -decrypt -inkey private.pem -in /tmp/envun -out /tmp/envdec
Getting a decrypted binary (?) key and using it do decrypt data in RC4:
openssl enc -d -rc4 -in encrypted -out decrypted -pass file:envdec
.
.
However, what I'm getting is:
bad magic number
Any advise?
Non crypted private key:
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCkBLH08f4nZBxiy2K9DXXmxeyqxcZtBIU3BjKDMO0jt2Lt4r6e
+MI/QFKVkms5iDUKaxPgwXptilR/f0KeLz7p2KbsAtDEFSPDWedd2/WYj2DYvoeF
+LskTYoWEyZsTbV7Vcm6lfzlZYggShtjlf6haHHTKo+FEp/ENmspni7n9wIDAQAB
AoGAFrTzshaCeg+ZAnBn1gZ0CSPjlOzWgKc8jhaUjacLXYN49bgLbdTAh6MvC7f+
kjNyLGQQl3ARs/KPqisDHQUrb1mPk2NBlMKk8SPf61D5VPcGyh1OwWSCSM9zg0AO
ZuBhi8RxZhkVAenBwmEAjHID/dA1wGj748uyuUMhq9noGbkCQQDZ/p/2QMGim5dc
KluTxUAtTuxtL5Cjn3rsCNvQiKbDE17zuZQD8O0lKaUIdWpmA9TTVxMXkGiPf/Lf
TApT6lVdAkEAwJ0KXjDsLc6h2lN6LEsm2siAj0fMnCLDUYaRmYB8Wz9S7JGWqE5O
AVg982FeYXxXe2mRL/cpKhbnGT8lvDQpYwJADuUlDPBzyqaS+wsx4rDxp6bi5LsB
SQzWm1YnnuIXcvDZ5hFiGbrWmVl1G1TahknwutgSR+PoIRX/BF7vvbgfSQJAIOYx
8Si2DpTuvFXp1kr31gLNQqvm3PxrFC/CCtARbZyBU3sCmrjVRhGGc128OzZ70s6T
R/gVheTnkD5i+aSHNQJAYGwKSmW7TQPZSlaHfs4vdSnOoxVpdqi/KJG3v+PPhz6R
2+8OZnjXk62VX05jMnMNnu9BMvP0CNjKIjnsOP7NoQ==
-----END RSA PRIVATE KEY-----
How it was encrypted:
$pub_key_ids = [];
$sealed = '';
$pub_key_string = file_get_contents("/usr/local/ssl/public.pem");
$pub_key = openssl_get_publickey($pub_key_string);
if ($pub_key) {
$pub_key_ids[] = $pub_key;
}
if (count($pub_key_ids)) {
if (openssl_seal($params['deployment_settings'], $sealed, $ekeys, $pub_key_ids) !== false) {
$data = base64_encode($sealed);
$envkey = base64_encode($ekeys[0]);
}
foreach ($pub_key_ids as $pub_key_id) {
openssl_free_key($pub_key_id);
}
}
As question stand for bash, there are some bashisms we could use:
All in one:
#!/bin/bash
openssl rc4 -d -in <(
base64 -i --decode <<eodatas
Y3jrrTI96HVK7aMR/LrLnCGsqlQNvpQN8TTEoClak2GHk1MMV5/Ig6CD5EuojJaIgey7
9XGjf8S9IqLsJ/MxOjODSFM48D+G0lbBW9GEOUFB027pfuHDhyMoTsxjEFBGXIz5
eodatas
) -iv 0 -K "$(
hexdump -v -e '/1 "%02X"' < <(
openssl rsautl -decrypt -inkey <(cat <<eoprivkey
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCkBLH08f4nZBxiy2K9DXXmxeyqxcZtBIU3BjKDMO0jt2Lt4r6e
+MI/QFKVkms5iDUKaxPgwXptilR/f0KeLz7p2KbsAtDEFSPDWedd2/WYj2DYvoeF
+LskTYoWEyZsTbV7Vcm6lfzlZYggShtjlf6haHHTKo+FEp/ENmspni7n9wIDAQAB
AoGAFrTzshaCeg+ZAnBn1gZ0CSPjlOzWgKc8jhaUjacLXYN49bgLbdTAh6MvC7f+
kjNyLGQQl3ARs/KPqisDHQUrb1mPk2NBlMKk8SPf61D5VPcGyh1OwWSCSM9zg0AO
ZuBhi8RxZhkVAenBwmEAjHID/dA1wGj748uyuUMhq9noGbkCQQDZ/p/2QMGim5dc
KluTxUAtTuxtL5Cjn3rsCNvQiKbDE17zuZQD8O0lKaUIdWpmA9TTVxMXkGiPf/Lf
TApT6lVdAkEAwJ0KXjDsLc6h2lN6LEsm2siAj0fMnCLDUYaRmYB8Wz9S7JGWqE5O
AVg982FeYXxXe2mRL/cpKhbnGT8lvDQpYwJADuUlDPBzyqaS+wsx4rDxp6bi5LsB
SQzWm1YnnuIXcvDZ5hFiGbrWmVl1G1TahknwutgSR+PoIRX/BF7vvbgfSQJAIOYx
8Si2DpTuvFXp1kr31gLNQqvm3PxrFC/CCtARbZyBU3sCmrjVRhGGc128OzZ70s6T
R/gVheTnkD5i+aSHNQJAYGwKSmW7TQPZSlaHfs4vdSnOoxVpdqi/KJG3v+PPhz6R
2+8OZnjXk62VX05jMnMNnu9BMvP0CNjKIjnsOP7NoQ==
-----END RSA PRIVATE KEY-----
eoprivkey
) -in <(base64 -i --decode <<eoenvkey
JJXy5kX9RNSd90BgRSKUX1AGZhwbzetVHKAZTv1/HCBEPGqaGvoWdxaiA8UaJAAr
mS7Sh3pbMm1GN41BYi2r4m9VONknIqn3VB+cikA7ZRxmKOVhRuJTgdjWhrCMyxls
1osAsC8lIFkLo13Z1v8IZAXKGIdyO86WHXzfQku8HAE=
eoenvkey
) ) )"
printf "\nResult: %s\n" $?
This could output:
A combination of genetic and environmental factors play a role in the development of schizophrenia.
Result: 0
By using functions
This could be more usefull:
#!/bin/bash
declare Data=./datas
declare Envkey=./envkey
declare PrivateKey=./privkey
b64Dec() { base64 -i --decode ; }
hxDump() { hexdump -e '/1 "%02X"' ; }
rsaDec() { openssl rsautl -decrypt -inkey $1 -in $2 ; }
rc4Dec() {
openssl rc4 -d -iv 0 -K "$1"
printf >&2 "\nResult: %s\n" $?
}
rc4Enc() {
openssl rc4 -iv 0 -K "$1"
printf >&2 "\nResult: %s\n" $?
}
declare Key="$(hxDump < <(rsaDec $PrivateKey <(b64Dec <$Envkey)))"
b64Dec <$Data | rc4Dec $Key
rc4Enc $Key <<eoGeorgOrwellQuote | base64
In our age there is no such thing as 'keeping out of politics.' All issues
are political issues, and politics itself is a mass of lies, evasions,
folly, hatred and schizophrenia.
-- George Orwell --
eoGeorgOrwellQuote
This could produce:
A combination of genetic and environmental factors play a role in the development of schizophrenia.
Result: 0
Result: 0
azaorSotoXpM/OoK+v/WnyGivBoGpd0dpDbC5H1XlHmJwV0RGt3NkqSfrUOuz42Sh7/04z2yaYi1
drngOLg2cxzPUBs0oyiWwUCnVdOMfF9an2j7N/HBg2o7Us9+B0YEFYy5oLISIRtZguZx2M6qYA9N
EJVDUG7mCL041jCszPAIKreV7PPnRCWt0MLyunv6MDSwJ3dppTUYcgXAL2vDxcIs/GYmbWh8sjgo
/t9fqxCM56a8xwUpityQh1JukHoFQyPzhOYUfNg85I2azhyLoX2OlQ==
Using openssl native command, you can do the following :
base64 --decode envkey > envun
openssl rsautl -decrypt -inkey private.pem -in envun -out envdec
KEY=$(cat envdec |hexdump -v -e '/1 "%02X"')
openssl rc4 -d -a -in encrypted -iv 0 -K "$KEY"
You have to use "-a" flag cause your content is base64 encoded.
You can use php in command line mode with "-q" to suppress the header.
php -q decrypt.php data.txt envkey private.pem
content of decrypt.php
<?php
$pkeyid=openssl_get_privatekey(file_get_contents($argv[3]));
$content=base64_decode(file_get_contents($argv[1]));
$envkey=base64_decode(file_get_contents($argv[2]));
if (openssl_open($content, $data, $envkey, $pkeyid)) {
echo "$data\n";
} else {
echo openssl_error_string()."\n";
}
openssl_free_key($pkeyid);
It will be far easier than using openssl native command.

PHP equivalent to OpenSSL RSA command

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;

Categories