PHP : Retrieving keys using openssl - php

I manage to generate private / public keys using the following script :
$res = openssl_pkey_new(array('private_key_bits' => 2048,'private_key_type' => OPENSSL_KEYTYPE_RSA));
openssl_pkey_export($res, $privkey);
file_put_contents('test.private.key', $privkey);
$pubkey = openssl_pkey_get_details($res);
$pubkey = $pubkey["key"];
file_put_contents('test.public.key', $pubkey);
The generated files :
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwQ5L0JQ2G5zGhC4uDISo6krN/mKrBuULYhrVL9Zdve+C9DuH
6uDTRCC07PvIKcHVj13vKB4YvRlwCCAxHg5p34P3W9vjmrI91rdVJ31noRvJ/i5Z
jNBfy7c8NrIOA6m4gicfPbozuQU741jLSncdQuyZRrADbFWppIz/mLm5WDZk6+NU
yAM2o0jvDsKE7i3sT+IKJpjUC8mE+RONIooNtHB3GJarsCKg5L6e0EaGXlVp9Mez
lSSn/Z5p1Wu3GJq02lNGLT5BVgCfE7ajBDZWRDG+Mbp4/YCt/zXz5XWm2/BxD78c
2wH3qMs/bIjvq5MTta4E2VQTSCxI5fMjRUf5QQIDAQABAoIBAQCvZuXLJF3kyJQ1
FCASj5VJCZ4POmZZZVDqWabIR+Pz5eD9NflPleVdSLoZdslt5wa5s4bO1El1xd7c
AyOdQ0s+IRBlDWvF6Zv1saxUrMOyxSTJJCOIpOnklR7IMw44lcNlvVXNJ5hGylKX
RN2vUnnrjDvW1aTGkS4Iq3KuuE+FrJIOm9Lb7z4Nj7BwmgwUtbB5NQKFDVohPp+w
pFGPHrN6dCy+qoSlY/IP89u6f7g9HBEM+n91uO6dQwSb/YxBROLMffXNJKA+UKex
UIIZlrPUcFN+yDVbQBmMFA3PYbBvwqZfpwzslIoUS+CGE/MorbW77/Qy2P4BC3/D
h8dmRDiBAoGBAOIDLHoMwT3FP+jlgZiAktQjShGRQJ+Li66L1nNIAJSeE8Nna5Sk
E3R1TBIZBmAGUZJ00POUWUMooAQIGF597hnFuENZIYpvulkKDCCUVx24kZDbyady
TcWdnEZfRmun5H7JfTlJl1HjqgGxKOc3ek/xDxoqiNf2WqScIom+dWndAoGBANqr
tQZyvpwv8FZVgkmteCCJb5NZzs04NzrT/i792/mL9Y45VxneLJVbXrAmQw/ClfVi
Z04NamqeOvVwUByoxWvZwLtyNt2dhpmtYlWuMRdo505BW1I75UIZYbWgZTtVq+PR
mf0SxNYXTsJQsqTTkqHQOMOHj8JyoAG1Z04J4qC1AoGAEkDpXa4cCU4d/ERU9Ckm
MqXq/II7sucFUAKRPlxJV7dwpy56HNYnkBdNHoUQ475+5hIzMgkAMJFeYxT4SuFm
0oQKfr37HIArj7dlBViVtJvMfeOSZMixiU1SasiVGmrD5I2HZJIR+5Yki+BwCkSL
x1sTuixHQxHtfi/yBifwua0CgYBPaGFRmSOc5k+5mk244bSo5B/Pe6J8pbhwtYEt
oWRbh7bBUhNOQn8gMdD92Lcrpvb76CMplfeaBiHU9VcyQRuIIcg6iaxg6A50CiGW
ia4sGR0+Lr+x6ixDx6HS6g8479B+56Oq4kD2mfow2Es3TdmGx22Fm9nZu/RdCnoc
Pby9rQKBgAak6zdKdMHzmHd+r2rbCTqT/NOIoip1zYpEGpiginkZcpy7Mz4iBL1Y
H7a2sa5k9Pykm2sQYoFPM8vn7halDcuAV7mjiV4XyiM5wRRWHTqSoUgjElexE0W5
HoQvWv10NBFqySMSfCm+YFXZGY17usxAJPSIySHzoTVRJEIjAw0G
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwQ5L0JQ2G5zGhC4uDISo
6krN/mKrBuULYhrVL9Zdve+C9DuH6uDTRCC07PvIKcHVj13vKB4YvRlwCCAxHg5p
34P3W9vjmrI91rdVJ31noRvJ/i5ZjNBfy7c8NrIOA6m4gicfPbozuQU741jLSncd
QuyZRrADbFWppIz/mLm5WDZk6+NUyAM2o0jvDsKE7i3sT+IKJpjUC8mE+RONIooN
tHB3GJarsCKg5L6e0EaGXlVp9MezlSSn/Z5p1Wu3GJq02lNGLT5BVgCfE7ajBDZW
RDG+Mbp4/YCt/zXz5XWm2/BxD78c2wH3qMs/bIjvq5MTta4E2VQTSCxI5fMjRUf5
QQIDAQAB
-----END PUBLIC KEY-----
Could someone tell me how to retrieve my keys, in order to encrypt / decrypt files. I'm trying the following :
$privkey = openssl_pkey_get_private('file://test.private.key')
$pubkey = openssl_pkey_get_public('file://test.public.key')
But these functions return false...
Thanks

Ok sorry forget about this post, I just tried to make it hard where it's very simple : A file_get_contents('test.public.key') is enough to retrieve the keys ;)

Related

JWT Token generated using firebase/php-jwt is showing as Invalid Token

I am using firebase/php-jwt for generating JWT Token using the following PHP Source Code
<?php
include '../vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC8kGa1pSjbSYZVebtTRBLxBz5H4i2p/llLCrEeQhta5kaQu/Rn
vuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t0tyazyZ8JXw+KgXTxldMPEL9
5+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4ehde/zUxo6UvS7UrBQIDAQAB
AoGAb/MXV46XxCFRxNuB8LyAtmLDgi/xRnTAlMHjSACddwkyKem8//8eZtw9fzxz
bWZ/1/doQOuHBGYZU8aDzzj59FZ78dyzNFoF91hbvZKkg+6wGyd/LrGVEB+Xre0J
Nil0GReM2AHDNZUYRv+HYJPIOrB0CRczLQsgFJ8K6aAD6F0CQQDzbpjYdx10qgK1
cP59UHiHjPZYC0loEsk7s+hUmT3QHerAQJMZWC11Qrn2N+ybwwNblDKv+s5qgMQ5
5tNoQ9IfAkEAxkyffU6ythpg/H0Ixe1I2rd0GbF05biIzO/i77Det3n4YsJVlDck
ZkcvY3SK2iRIL4c9yY6hlIhs+K9wXTtGWwJBAO9Dskl48mO7woPR9uD22jDpNSwe
k90OMepTjzSvlhjbfuPN1IdhqvSJTDychRwn1kIJ7LQZgQ8fVz9OCFZ/6qMCQGOb
qaGwHmUK6xzpUbbacnYrIM6nLSkXgOAwv7XXCojvY614ILTK3iXiLBOxPu5Eu13k
eUz9sHyD6vkgZzjtxXECQAkp4Xerf5TGfQXGXhxIX52yH+N2LtujCdkQZjXAsGdm
B2zNzvrlgRmgBrklMTrMYgm1NPcW+bRLGcwgW2PTvNM=
-----END RSA PRIVATE KEY-----
EOD;
$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8kGa1pSjbSYZVebtTRBLxBz5H
4i2p/llLCrEeQhta5kaQu/RnvuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t
0tyazyZ8JXw+KgXTxldMPEL95+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4
ehde/zUxo6UvS7UrBQIDAQAB
-----END PUBLIC KEY-----
EOD;
$payload = [
'iss' => 'example.org',
'aud' => 'example.com',
'iat' => time(),
'nbf' => time() + 3600,
];
$jwt = JWT::encode($payload, $privateKey, 'RS256');
echo "Encode:\n" . print_r($jwt, true) . "<br/><br/>";
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
*/
$decoded_array = (array) $decoded;
echo "Decode:\n" . print_r($decoded_array, true) . "<br/>";
The code works fine, I am able to decode the Token properly, but when I try to verify the token using the Debugger on https://jwt.io/, it's giving an error saying, it's an invalid token.
Here is the JWT.io link with all the fields.
Note: I have read all the related questions and I am posting this question since they are unable to fix my issue.
Thanks in advance!!!
Screenshot:
Your key size is 1024 bit:
# key.pem is
# -----BEGIN RSA PRIVATE KEY-----
# MIICXAIBAAKBgQC8kGa1p...
# ...
openssl rsa -text -noout -in key.pem
RSA Private-Key: (1024 bit, 2 primes)
Now let's check for minimum requirements for RS256:
Required key size: At least 2048 bits
You have to create more secured key

How to convert PEM format RSA key into XML format using PHP

I'm trying to convert key pair from PEM format :
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
Into XML format :
<RSAKeyValue>
<Exponent> </Exponent>
<Modulus> </Modulus>
</RSAKeyValue>
Is it possible using only openssl as I generate the keys through it ?
nb : my keys are stored into $privKey and $pubKey variable for test purpose, so I want to be able to $echo the XML format key and not store it into a file for the moment.
nb' : I have tried using phpseclib with an exemple found here but it gives me this error "Uncaught Error: Class "BaseController" not found in ..."
Thanks for your help
Here is the PHP code :
<?php
$config = array
(
'config' => 'C:\xampp\htdocs\crypto\openssl.cnf',
'default_md' => 'sha512',
'private_key_bits' => 4096,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
);
$keypair = openssl_pkey_new($config);
openssl_pkey_export($keypair, $privKey, null, $config);
$publickey = openssl_pkey_get_details($keypair);
$pubKey = $publickey['key'];
use phpseclib3\Crypt\RSA;
echo $pubKey->toString("XML");
echo "$privKey";
?>
The conversion of a PEM encoded key in X.509/SPKI format to XML format can be done with phpseclib as follows:
use phpseclib3\Crypt\PublicKeyLoader;
$x509pem = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAunF5aDa6HCfLMMI/MZLT
5hDk304CU+ypFMFiBjowQdUMQKYHZ+fklB7GpLxCatxYJ/hZ7rjfHH3Klq20/Y1E
bYDRopyTSfkrTzPzwsX4Ur/l25CtdQldhHCTMgwf/Ev/buBNobfzdZE+Dhdv5lQw
KtjI43lDKvAi5kEet2TFwfJcJrBiRJeEcLfVgWTXGRQn7gngWKykUu5rS83eAU1x
H9FLojQfyia89/EykiOO7/3UWwd+MATZ9HLjSx2/Lf3g2jr81eifEmYDlri/OZp4
OhZu+0Bo1LXloCTe+vmIQ2YCX7EatUOuyQMt2Vwx4uV+d/A3DP6PtMGBKpF8St4i
GwIDAQAB
-----END PUBLIC KEY-----';
$publicKey = PublicKeyLoader::load($x509pem); // import public PEM key
$xmlFormattedKey = $publicKey->toString("XML"); // export public XML key
print($xmlFormattedKey);
The output is:
<RSAKeyValue>
<Modulus>unF5aDa6HCfLMMI/MZLT5hDk304CU+ypFMFiBjowQdUMQKYHZ+fklB7GpLxCatxYJ/hZ7rjfHH3Klq20/Y1EbYDRopyTSfkrTzPzwsX4Ur/l25CtdQldhHCTMgwf/Ev/buBNobfzdZE+Dhdv5lQwKtjI43lDKvAi5kEet2TFwfJcJrBiRJeEcLfVgWTXGRQn7gngWKykUu5rS83eAU1xH9FLojQfyia89/EykiOO7/3UWwd+MATZ9HLjSx2/Lf3g2jr81eifEmYDlri/OZp4OhZu+0Bo1LXloCTe+vmIQ2YCX7EatUOuyQMt2Vwx4uV+d/A3DP6PtMGBKpF8St4iGw==</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
For key generation OpenSSL can be used as in your code. However, the exported PEM key must be imported in the phpseclib part as shown in the code above (this import is missing in your code):
// Key generation with OpenSSL
$config = array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config); // create key resource using $config
//openssl_pkey_export($res, $privKey); // export private key (PEM encoded, PKCS#8 format); not required for this example
$pubKeyDetails = openssl_pkey_get_details($res);
$x509pem = $pubKeyDetails["key"]; // export public key (PEM encoded, X.509 format)
// Key conversion with phpseclib
$publicKey = PublicKeyLoader::load($x509pem); // import public PEM key generated with OpenSSL
$xmlFormattedKey = $publicKey->toString("XML"); // export public XML key
print($xmlFormattedKey);
Alternatively, also key generation can be done with phpseclib:
use phpseclib3\Crypt\RSA;
$privateKey = RSA::createKey(2048); // generate private key
$xmlFormattedKey = $privateKey->getPublicKey()->toString("XML"); // export public XML key
print($xmlFormattedKey);

PHP : Get private key from a single line private key

I am trying to create a JWT token. The other server is storing the public key in a single line and using that for validation.
Also, the public key being used for validation is in single line.
So, to generate the correct JWT token, what I think is I should also use the private key in a single line (may be with \n or may be without).
I am using openssl_sign to generate the token, which uses openssl_reource as key. I get that paramter from openssl_pkey_get_private.
But problem which happens in this case is, it either accepts the pem file path, or the key in PEM string format. So, if I pass the private_key as a single line, it doesn't give me the required output.
So, how can I resolve this. As I see other language libraries able to generate signature by passing private key in a single line.
In PHP the key can be formatted with line breaks or as a one-liner (with \n). Both works. In the following example I use a 512-bit encrypted RSA-key for simplicity (although in practice a larger key (>= 2048 bit) must be used for security reasons):
<?php
// Private key: 512 bit for simplicity
// Passphrase: MyPassphrase
// openssl genrsa -aes256 -out private.pem 512
$privKeyEnc = "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,8F2D6F9594B3D379BF9D9748BD174458
RP2fyz1VNBKHiCadC5B9fjxV7z7AMAqbsN2vykFfPhdUFsxlJaecEeTMT7s6IbZN
Pr80+ljLjJ0SxJiK+j8DAc/Wrf+qyYUFcWbsvOhUIPyB5ww9+mEeIERJCigsyZJ7
k/Apau/BypdC9vCXKB3wM9FcmvP1g/ZwVoXfN3TIPEfWTktvuf74yFNoIaVbZAK/
+tzAGduu9wLkr6WTq4Isqy/IPjVCp9VwH1wNnz+hjkO7oELcCpFieIvAidUMKBR9
EdexLQCimbOl2wlfRNLincK8+FDOVWx6ElFFQlhzyWQCt8ed1fdiAggKxOco4Ww2
tFjIzaO4KXlbc9JFGd9PzigpftN/aHbk3c+x0E+3q5u8eySai4vgk38s1KaE7rn/
rarCgtGxOlbbTkI3opkjIrGlrsEyexKtS23mI/Dgcco=
-----END RSA PRIVATE KEY-----";
// One-liner using \n
$privKeyEnc_1Line = "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-256-CBC,8F2D6F9594B3D379BF9D9748BD174458\n\nRP2fyz1VNBKHiCadC5B9fjxV7z7AMAqbsN2vykFfPhdUFsxlJaecEeTMT7s6IbZN\nPr80+ljLjJ0SxJiK+j8DAc/Wrf+qyYUFcWbsvOhUIPyB5ww9+mEeIERJCigsyZJ7\nk/Apau/BypdC9vCXKB3wM9FcmvP1g/ZwVoXfN3TIPEfWTktvuf74yFNoIaVbZAK/\n+tzAGduu9wLkr6WTq4Isqy/IPjVCp9VwH1wNnz+hjkO7oELcCpFieIvAidUMKBR9\nEdexLQCimbOl2wlfRNLincK8+FDOVWx6ElFFQlhzyWQCt8ed1fdiAggKxOco4Ww2\ntFjIzaO4KXlbc9JFGd9PzigpftN/aHbk3c+x0E+3q5u8eySai4vgk38s1KaE7rn/\nrarCgtGxOlbbTkI3opkjIrGlrsEyexKtS23mI/Dgcco=\n-----END RSA PRIVATE KEY-----";
// Public key:
// Passphrase: MyPassphrase
// openssl rsa -in private.pem -outform PEM -pubout -out public.pem
$pubKey = "-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMjYQLbdIVgKX1mSyKijOIpmlB9YWui1
KoCniRNHUPEsxth+o9fZXZMo1gzh9ZlFs6VLiyU7kv2+5QElOnhNzwcCAwEAAQ==
-----END PUBLIC KEY-----";
// One-liner using \n
$pubKey_1Line = "-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMjYQLbdIVgKX1mSyKijOIpmlB9YWui1\nKoCniRNHUPEsxth+o9fZXZMo1gzh9ZlFs6VLiyU7kv2+5QElOnhNzwcCAwEAAQ==\n-----END PUBLIC KEY-----";
$dataToSign = 'The quick brown fox jumps over the lazy dog.';
// Signing
//$privateKey = openssl_pkey_get_private("$privKeyEnc", "MyPassphrase"); // also works
$privateKey = openssl_pkey_get_private("$privKeyEnc_1Line", "MyPassphrase");
openssl_sign($dataToSign, $signature, $privateKey, 'sha256');
$signatureBase64 = base64_encode($signature);
print("Signature (Base64): ".$signatureBase64."<br>");
// Verifying
$publicKey = openssl_pkey_get_public("$pubKey");
//$publicKey = openssl_pkey_get_public("$pubKey_1Line"); // also works
$verified = openssl_verify($dataToSign, $signature, $publicKey,'sha256');
print("Verification: ".$verified."<br>");
/*
Output:
Signature (Base64): KVuUd+xy6at0emmhF20rbiD9lWzIN9euwKbeEm7aMvxqEkJ68HrjAoDJ37R3QGPI24woXY3TON9pahAhx+YNhQ==
Verification: 1
*/
?>

RSA256 public key from Google certs failing for one key

To authenticate a google oauth2 token, I'm generating a public key for kid "b863b534069bfc0207197bcf831320d1cdc2cee2" from the modulus (n) and exponent (e) from:
https://www.googleapis.com/oauth2/v3/certs
{
"alg": "RS256",
"n": "8h6tCwOYDPtzyFivNaIguQVc_yBO5eOA2kUu_MAN8s4VWn8tIfCbVvcAz3yNwQuGpkdNg8gTk9QmReXl4SE8m7aCa0iRcBBWLyPUt6TM1RkYE51rOGYhjWxo9V8ogMXSBclE6x0t8qFY00l5O34gjYzXtyvyBX7Sw5mGuNLVAzq2nsCTnIsHrIaBy70IKU3FLsJ_PRYyViXP1nfo9872q3mtn7bJ7_hqss0vDgUiNAqPztVIsrZinFbaTgXjLhBlUjFWgJx_g4p76CJkjQ3-puZRU5A0D04KvqQ_0AWcN1Q8pvwQ9V4uGHm6Bop9nUhIcZJYjjlTM9Pkx_JnVOfekw",
"use": "sig",
"kid": "b863b534069bfc0207197bcf831320d1cdc2cee2",
"e": "AQAB",
"kty": "RSA"
}
I then create the RSA 256 public key in php with:
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64url_decode($cert["n"]), 256);
$exponent = new Math_BigInteger(base64url_decode($cert["e"]), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
$public_key = $rsa->getPublicKey();
This generates public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuopEuQyOKMsQq90I/5on
1nNBPc7stMvsN1HC+Pgyu8nJ1qWwaAAqIv4edo2oG/Bo3eg6p+OjG3nbFL62S6hE
aJLUVfxhW5GQuxQlsvaA2MsZuZCRyKTv8bm641wM+biGVZLiDsLRylVdpxf4aGa9
9zZw+QZMVKL4f9B4SunyTugTaCIu8LBOQesCQp/QJaUjqMDhfEvoFQXiCn6zo3rW
EWBiKxiFBizH9jSfWimJecFhn0Vlv/Vs7pRb0X2y66VS3gTvR6/A3ooNz3tYAJPM
GoE8fAiEghYXXHjmWmgdRx9Qt9sa/ACwv7yx0Th27fw+rrsMSrUyaqRpn/fjIMTu
sQIDAQAB
-----END PUBLIC KEY-----
This same method worked with dozens of other RS256 kid's from google, but the public key does not work with this particular kid.
I am verifying the signature with:
openssl_verify($payload_to_verify, $safe_signature, $public_key, OPENSSL_ALGO_SHA256);
Which responds with '0' for failure.
Edit #2: Found google's version of the public key at:
https://www.googleapis.com/oauth2/v1/certs
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8h6tCwOYDPtzyFivNaIg
uQVc/yBO5eOA2kUu/MAN8s4VWn8tIfCbVvcAz3yNwQuGpkdNg8gTk9QmReXl4SE8
m7aCa0iRcBBWLyPUt6TM1RkYE51rOGYhjWxo9V8ogMXSBclE6x0t8qFY00l5O34g
jYzXtyvyBX7Sw5mGuNLVAzq2nsCTnIsHrIaBy70IKU3FLsJ/PRYyViXP1nfo9872
q3mtn7bJ7/hqss0vDgUiNAqPztVIsrZinFbaTgXjLhBlUjFWgJx/g4p76CJkjQ3+
puZRU5A0D04KvqQ/0AWcN1Q8pvwQ9V4uGHm6Bop9nUhIcZJYjjlTM9Pkx/JnVOfe
kwIDAQAB
-----END PUBLIC KEY-----
My generated public key is different. Why my generated public key is wrong?
I confirm that the key is not correctly converted by the RSA Crypt package.
Wrong key
Good key
I tried to convert that key with another application (web-token/jwt-app) and I got the same result as the one provided by Google.
curl -OL https://github.com/web-token/jwt-app/raw/gh-pages/jose.phar
curl -OL https://github.com/web-token/jwt-app/raw/gh-pages/jose.phar.pubkey
chmod +x jose.phar
./jose.phar key:convert:pkcs1 '{"alg": "RS256","n": "8h6tCwOYDPtzyFivNaIguQVc_yBO5eOA2kUu_MAN8s4VWn8tIfCbVvcAz3yNwQuGpkdNg8gTk9QmReXl4SE8m7aCa0iRcBBWLyPUt6TM1RkYE51rOGYhjWxo9V8ogMXSBclE6x0t8qFY00l5O34gjYzXtyvyBX7Sw5mGuNLVAzq2nsCTnIsHrIaBy70IKU3FLsJ_PRYyViXP1nfo9872q3mtn7bJ7_hqss0vDgUiNAqPztVIsrZinFbaTgXjLhBlUjFWgJx_g4p76CJkjQ3-puZRU5A0D04KvqQ_0AWcN1Q8pvwQ9V4uGHm6Bop9nUhIcZJYjjlTM9Pkx_JnVOfekw","use": "sig","kid": "b863b534069bfc0207197bcf831320d1cdc2cee2","e": "AQAB","kty": "RSA"}'
Best would be to warn phpseclib/phpseclib about that issue.

RSA decryption doesn't work

I trying to encrypt and decrypt a simple string with PHPseclib, but when I try to decrypt it, the result is null or empty. Could any one help me please?
here are my functions
public function myEncrypt($conteudoArquivo, $private_key) {
$rsa = new Crypt_RSA();
$rsa->loadKey($private_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$cipherText = base64_encode($rsa->encrypt($conteudoArquivo));
return $cipherText;
}
public function myDecrypt($cipherText, $public_key) {
$rsa = new Crypt_RSA();
$rsa->loadKey($public_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$plainText = base64_decode($rsa->decrypt($cipherText));
return $plainText;
}
and the keys values are:
$private_key = "-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCRwpD+gV0skm+9SHPWFXAHkWV3r37I3N4fom45Z0imih3fDk9E
Q6PuFb56Vfo8IWiNUoP6Gco/eDHcInzO1SSEn07reh86Aosnnj7m/RMg1N5k7A5C
NH26YlATqgJe4DX8SdS/oKLit7xTo3aR+Wg3kZOQQmE5MyRq6TVDywhNyQIDAQAB
AoGAVFk4mN75sUJogSu9RMURGIAOLM2U293ceIgBqxxW0XEZyiu4uTM/WRaiLJ82
eLeIjkeS8hccj9AZYl9exD5Zq7oGTH8HDQAcmZ6p0h3faI1/sR3gnqEB28GZJyd7
MsFRlRiOEdpJAki33m/6UsJ7hRHC6X/w2K4wofzmmHopOIECQQDCAMW7gc4Gmyb1
scP8OwA75QZWgeLo36d7ynUzjqoN682ckSbIxbT6z4eYhEKE/It0gt07WTNmrL0s
vv4DH15xAkEAwFcTC1/FufpDvxt+EKnANmuH5ekri1zcsY3UMJJnjH9e7szfVTH6
JfhTRRSfi/oOe1aRinfcp/zMJhkf36VA2QJAO8K5JlWJ/Yb1rWGhGaWjINAf7637
E/kxQnTPPZ6Iy9kDcWNVKyub4FblUhoL06Nn4fAd7hZAOzSi4ZHD9XpIQQJAc1MC
QTygcp1jB3A1i0oszLR23FyNVldMoE044BK4cZ5hTm+arRt1MFUPoIj4DNbW3g8O
3uZ1cGf8BA/mc5NDKQJAexm+LcJ3DOTaenQwHw77bfXhbvvCtcvAlYOIawkyDlTx
AkBweqy8BEJbsVRSiBv7k6Hh+T+u1ZWaKDm/ZZCMkA==
-----END RSA PRIVATE KEY----- ";
$public_key = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HK
U0jQjX/n/db9vz/x0i3te/bKLNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJA
HmbrNtrUB6ckrYLF75Y50nUNsBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQAB
-----END PUBLIC KEY-----";
You need to encrypt with the public key and decrypt with the private key. That is how asymmetric encryption works. In RSA "encrypting" with the private key is actually signing and "decrypting" with the public key is verification of the signature.
The other thing is that you don't reverse the Base64 encoding properly. So you need to first decode and then decrypt:
$plainText = $rsa->decrypt(base64_decode($cipherText));
The keys you presented cannot be used with this code, because they have a different modulus. You can generate the keys this way:
$rsa = new Crypt_RSA();
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$keys = $rsa->createKey(2048);
$private_key = $keys["privatekey"];
$public_key = $keys["publickey"];

Categories