RSA Decryption with phpseclib is failing - php

I have mobile application that encrypts strings with RSA and sends that encrypted data to PHP web server.
After a search I found that phpseclib is used to decrypt RSA
Latest version 2.0.
No matter what I do I receive despite error despite used mode
Am i doing something wrong?
What I have tried:
Private key for decryption:
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAJyHUgC1ijhsETeuoNMh4c4yrFoL4juL/yDderMC9fBd1TFgEoJ5dxzMzdlzVVj7Vc/H/I+k13yY3W0MknS//k8CAwEAAQJAaaL1l57s8lkUYZTL2tFh9+vA32BnxLIdc0ullAwqeJV21wXcEyDA67fbmBywdt+pVKkeO2NU7fD3e+DZREuJ0QIhAPZNo9jirkRl4i/Lv3jWt6SmeUBeyIKK0u4lZiBF9KAZAiEAorDjj2c9WBdP46S9hK7yj0U5/0QHB0pO01j9QSVBvqcCIQDrYre7hqdU5qmLVATgzxMiX5ZxViP53gJHZaZ8IV7vwQIgTTYEGafWjjsqGBC0PQdGaMZi+wnPCB+0/0rpjoRfClsCIBPzZw+lappnVxXHuUoQQeN6uevqSvmgvC42UyA4HABa
-----END RSA PRIVATE KEY-----
Encrypted message (base64 encoded):
SMZiVTAMizngWa5Yg2Xp0F3Coy4cIsLB6mru2rLhxnvS2SC\/rm9pgPVLdA\/hp+1TIbzHZqjc2lnP\nkvzh797WlA==\n
PHP sample code:
$rsa = new RSA();
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$rsa->loadKey($privateKey);
echo $rsa->decrypt(base64_decode($strBase64));
Result:
Notice: Decryption error in C:\xampp\htdocs\webservice\vendor\phpseclib\phpseclib\phpseclib\Crypt\RSA.php on line 2553
Mode:
$rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP);
Result:
Notice: Decryption error in C:\xampp\htdocs\webservice\vendor\phpseclib\phpseclib\phpseclib\Crypt\RSA.php on line 2432
Mode:
$rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);
Result:
string(128) "I�W��B'q����;k��}�1������=��x���*���_��aq�)�D� '�m{��� ��n���C:��t �E����R=�S�y�3$QC�EV.3C�{�.Y�jx�6��!�e�˱]�I ����S�/�'I�|"

As James J Polk observed, your base64 encoded string has some bad characters in it. idk what you're using in PHP as your delimiter but this worked for me:
$strBase64 = 'SMZiVTAMizngWa5Yg2Xp0F3Coy4cIsLB6mru2rLhxnvS2SC\/rm9pgPVLdA\/hp+1TIbzHZqjc2lnP\nkvzh797WlA==\n';
$strBase64 = str_replace(['\/', '\n'], ['/', ''], $strBase64);
If you're using double quotes instead of single quotes do this:
$strBase64 = "SMZiVTAMizngWa5Yg2Xp0F3Coy4cIsLB6mru2rLhxnvS2SC\/rm9pgPVLdA\/hp+1TIbzHZqjc2lnP\nkvzh797WlA==\n";
$strBase64 = str_replace(['\/', "\n"], ['/', ''], $strBase64);

$rsa = new RSA();
$rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP);
$ciphertext = base64_decode($string);
$rsa->setMGFHash('sha1');
$rsa->setHash('sha256');
$rsa->loadKey($pkey); // public key
$output = $rsa->decrypt($ciphertext);
return $output;

Related

Can't decrypt any message with openssl_private_decrypt

I try to decrypt RSA encrypted message from php with openssl_private_decrypt function. But the function always return null.
My function is the following :
function (){
$encrypted = 'gu6F7PFj2t+Mchp2Vi8dpiEXXVDkrjrSoOnRlCWeZYjOL6WdjvxULyEG5j9dZPORNMYx5eB9gTdni4NYYCKW3GTGS0zaKGgadChy/KZAUo40sBVmTFN3YOT6FfEr4oXZ9c0DqSRJ/LrZsZvsiHh52LleA9sapOgsm0bsgWzgnnE=';
$privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCMeu1UGlPod+yC/cD+qDWRyotkKly7A+gD+twgekiTguZUJPJl
ZnB2JpL/cU9oO9nOKn6WJ4DGy7qNjuOj7sLvIkgekPjW6RA2LgOgmS9gSKeOb1OI
i59QdoyNv6xOblPz7ihsc5g/KsKEVCLeP5RfBXRXEzS0KHbBnQ3zS8PktwIDAQAB
AoGASZJ7xyc+uKpOCNCDChvoamFsnVn+VMeX9LWmIbBJYFAW9wyeknKTBZ3wMK4U
S1/FE094GoW30OWT311tZUa/ehtKA0M9ODCk/Sx9eWxq/oR1e6ypJS8zzKG47DD3
3+PxKGh+IPJXo8qINvxj7yYbjMxydo8xvBufuBgjoaU9r7ECQQDcsOZIuhvhyWkf
fJFjmyFYPNJD8eJBQZnxk9uIH/yDl5vJ+bf7fNFc3t+Epnjqfgf98W5frLUeYuzT
reusJHF5AkEAovS9EowcIeMp3Ce1utSdGZpjAkGdwVwnxhDLnyO2/TuKNpYODOS7
/bLS3NCg9Kw6UF1VLltFwjsBcSoyDmMrrwJAQOMOQlHeAsvaSbSxdqzU6AGx/OIw
mOk13w6PHH3zG6nG12LB0oKHeBvbckAUCzYVGXgT8LNx6UZCxZY8Vbe9WQJAZbTq
7VCVnnDyB36hZmKdSwWZFiduFuk1yeFhtYnNBHDM6xTs4A9DZizefwOX8h4sp0wZ
hj1hZMD/PWpgo6ox8QJAFYMky0FT8n19mNRN9aGkQ2GDqO+F8jLEnFJMPXJMGyCg
85CGeRH9sF69skcNToZMR304Ms/xyfLeG72SksHT7g==
-----END RSA PRIVATE KEY-----';
return openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);
}
The decrypted is the following : Salut les amis
You can slightly modify your code to detect the error
function (){
$encrypted = 'gu6F7PFj2t+Mchp2Vi8dpiEXXVDkrjrSoOnRlCWeZYjOL6WdjvxULyEG5j9dZPORNMYx5eB9gTdni4NYYCKW3GTGS0zaKGgadChy/KZAUo40sBVmTFN3YOT6FfEr4oXZ9c0DqSRJ/LrZsZvsiHh52LleA9sapOgsm0bsgWzgnnE=';
$privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCMeu1UGlPod+yC/cD+qDWRyotkKly7A+gD+twgekiTguZUJPJl
ZnB2JpL/cU9oO9nOKn6WJ4DGy7qNjuOj7sLvIkgekPjW6RA2LgOgmS9gSKeOb1OI
i59QdoyNv6xOblPz7ihsc5g/KsKEVCLeP5RfBXRXEzS0KHbBnQ3zS8PktwIDAQAB
AoGASZJ7xyc+uKpOCNCDChvoamFsnVn+VMeX9LWmIbBJYFAW9wyeknKTBZ3wMK4U
S1/FE094GoW30OWT311tZUa/ehtKA0M9ODCk/Sx9eWxq/oR1e6ypJS8zzKG47DD3
3+PxKGh+IPJXo8qINvxj7yYbjMxydo8xvBufuBgjoaU9r7ECQQDcsOZIuhvhyWkf
fJFjmyFYPNJD8eJBQZnxk9uIH/yDl5vJ+bf7fNFc3t+Epnjqfgf98W5frLUeYuzT
reusJHF5AkEAovS9EowcIeMp3Ce1utSdGZpjAkGdwVwnxhDLnyO2/TuKNpYODOS7
/bLS3NCg9Kw6UF1VLltFwjsBcSoyDmMrrwJAQOMOQlHeAsvaSbSxdqzU6AGx/OIw
mOk13w6PHH3zG6nG12LB0oKHeBvbckAUCzYVGXgT8LNx6UZCxZY8Vbe9WQJAZbTq
7VCVnnDyB36hZmKdSwWZFiduFuk1yeFhtYnNBHDM6xTs4A9DZizefwOX8h4sp0wZ
hj1hZMD/PWpgo6ox8QJAFYMky0FT8n19mNRN9aGkQ2GDqO+F8jLEnFJMPXJMGyCg
85CGeRH9sF69skcNToZMR304Ms/xyfLeG72SksHT7g==
-----END RSA PRIVATE KEY-----';
if (!openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey)) {
throw new Exception(openssl_error_string());
}
return $decrypted;
}
The result on my machine is:
PHP Fatal error: Uncaught Exception: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error in /home/foobar/test.php:20
So, there is a "pkcs decoding error" when decoding your encrypted string. And your openssl_private_decrypt failed to decrypt your message. Please check the way you encrypted / base64_encode the text to see if you have any mistake there.

Javascript pidCrypt RSA and PHP RSA decryption

i'm working on a site that invovles storing public/private RSA encrypted content, until recently i've been doing it all via javascript. I now need to be able to encrypt with public key in PHP, i've lost the last 6 hours to this problem. I'm willing to change libraries if needbe, but currently im trying this:
https://www.pidder.de/pidcrypt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BkQXJ4pCsGC8mrHXF3M+hJV+
+LAYJbXrQa4mre59wR0skgb6CwGg1siMrDzJgu3lmBB0
-----END RSA PRIVATE KEY-----";
/*
PHP code using phpseclib:"
$rsa = new Crypt_RSA();
//extract($rsa->createKey());
$plaintext = 'eKFqZhGXg/QzTKI9dbvamIxDSltVWoz73DSowr87ipWHRSqKBAE463VCrcNcDKyW
gleCanPtV4NQ0qEImhf2xpIHFPeaCc++a0u7ZhZF8vpn5E8AGz97lqs3o7XGwmm1
EUlCeHh3c6574wiUd93eWBWLhxQUJPK66V3CQT0SrEQ=
';
$plaintext=base64_decode($plaintext);
$rsa->loadKey($priv_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->decrypt($plaintext);
echo $ciphertext;
just echoing empty text, the plaintext variable is data encrypted via the pidcrypt website using those keys. why isnt this working? i've also tried running it through openssl:
$res = openssl_get_privatekey($priv_key);
/*
* NOTE: Here you use the returned resource value
*/
openssl_private_decrypt($plaintext,$newsource,$res);
echo "String decrypt : $newsource";
also did not work. i've read and everythibng says pidcrypt is openssl compatible. i just cant seem to figure it out.
This works for me:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDVd/gb2ORdLI7nTRHJR8C5EHs4RkRBcQuQdHkZ6eq0xnV2f0hk
WC8h0mYH/bmelb5ribwulMwzFkuktXoufqzoft6Q6jLQRnkNJGRP6yA4bXqXfKYj
1yeMusIPyIb3CTJT/gfZ40oli6szwu4DoFs66IZpJLv4qxU9hqu6NtJ+8QIDAQAB
AoGADbnXFENP+8W/spO8Dws0EzJCGg46mVKhgbpbhxUJaHJSXzoz92/MKAqVUPI5
mz7ZraR/mycqMia+2mpo3tB6YaKiOpjf9J6j+VGGO5sfRY/5VNGVEQ+JLiV0pUmM
doq8n2ZhKdSd5hZ4ulb4MFygzV4bmH29aIMvogMqx2Gkp3kCQQDx0UvBoNByr5hO
Rl0WmDiDMdWa9IkKD+EkUItR1XjpsfEQcwXet/3QlAqYf+FE/LBcnA79NdBGxoyJ
XS+O/p4rAkEA4f0JMSnIgjl7Tm3TpNmbHb7tsAHggWIrPstCuHCbNclmROfMvcDE
r560i1rbOtuvq5F/3BQs+QOnOIz1jLslUwJAbyEGNZfX87yqu94uTYHrBq/SQIH8
sHkXuH6jaBo4lP1HkY2qtu3LYR2HuQmb1v5hdk3pvYgLjVsVntMKVibBPQJBAKd2
Dj20LLTzS4BOuirKZbuhJBjtCyRVTp51mLd8Gke9Ol+NNZbXJejNvhQV+6ad7ItC
gnDfMoRERMIPElZ6x6kCQQCP45DVojZduLRuhJtzBkQXJ4pCsGC8mrHXF3M+hJV+
+LAYJbXrQa4mre59wR0skgb6CwGg1siMrDzJgu3lmBB0
-----END RSA PRIVATE KEY-----');
$ciphertext = 'B0xBiIroAo7xpHuDThpsAIAAlmlJtK1M0I4wGSJQuRMj5vy0g/+QeDYA4v+9Pl5m
R/eiXzmbNF/WrBNJkgTJQalXK8zLGXFs1YxSnpVazBIAZo+zrnwy6g0eZ4U6exEx
tVcU/ay+oRa+K0Rn03N29y3wi5Dy46hTSLQW12a7zLY=';
$ciphertext = 'wYevij6cVGuf6+675lL81dK4oQxxINn0ESWOIKDe76u9iAdzg5JwJGuiealOAKDY
GQPCzWFtY4i+xpC3lbxc01tuzwLqLDyc78d5ejmEMraPdToaX+Z7+naiabXUUQlg
PSxsVlpL9b5S6/kB9BVJK9aOYMBlonJEKs9IZKKuoVw=';
$ciphertext = str_replace(array("\r","\n",' '), '', $ciphertext);
$ciphertext = base64_decode($ciphertext);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo base64_decode($rsa->decrypt($ciphertext));
That's using the default public / private key pair at https://www.pidder.de/pidcrypt/?page=demo_rsa-encryption . The ciphertext came from that page as well.
My guess as to what you're doing wrong: you're copy / pasting the text from the "Encrypted text" textbox but aren't removing the new line characters.

Votifier PHP Encryption

I've been trying to add votifier functionality to my site but so far, without any luck at all.
My problem is that the encryption using the openssl_public_encrypt returns an empty response.
Here's my code: http://pastebin.com/wakjcxSF
I call it like this:
$vote = new Vote(USERNAME, SERVERIP, SERVERPORT, VOTIFIERKEY);
$vote->castVote();
The output of the print_r:
0
VOTE Something test 127.0.0.1 1376050280
-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiRda9+W9mXLz1Mvc4hXMo rea2NPPJVgbQCypwpgIUK0Q7vQ2sK+Om2yCyTtwIvdOCAa1Uh+cX2Drs3xHkPutw/ rkTiFEWWQ3ol3jxMm+5BXUSESSK+P26nr7JvFddnOdVM1FFVCwFXYmYIwigeXK3lO qrOLFdxVEbpG5wEcNPOVIqq1RKfKQIFGvYfIVpRCaj3yMRlSK4S1jQtlqMy5Tnva+ xqaFjEHN2QJRwLecmkPnGsWicEfoc+khV64/06YKg5Becqx69sS+snY8SM1E/atZk b/eqm165A7Awzw3e9Fl2Uk4F7kUwrRGZDjzu6knr6Vr13slXDxzEKd33xv8/QIDAQ AB -----END PUBLIC KEY-----
Original public key:
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiRda9+W9mXLz1Mvc4hXMorea2NPPJVgbQCypwpgIUK0Q7vQ2sK+Om2yCyTtwIvdOCAa1Uh+cX2Drs3xHkPutw/rkTiFEWWQ3ol3jxMm+5BXUSESSK+P26nr7JvFddnOdVM1FFVCwFXYmYIwigeXK3lOqrOLFdxVEbpG5wEcNPOVIqq1RKfKQIFGvYfIVpRCaj3yMRlSK4S1jQtlqMy5Tnva+xqaFjEHN2QJRwLecmkPnGsWicEfoc+khV64/06YKg5Becqx69sS+snY8SM1E/atZkb/eqm165A7Awzw3e9Fl2Uk4F7kUwrRGZDjzu6knr6Vr13slXDxzEKd33xv8/QIDAQAB
I used this tutorial: http://topg.org/php_votifier.
I tried to look around on google but the problems was invalid key problems. Result:
google (com)/search?q=Votifier+PHP+Encryption&oq=Votifier+PHP+Encryption&aqs=chrome.0.69i59j69i60j69i62l2.6301j0&sourceid=chrome&ie=UTF-8#bav=on.2,or.r_cp.r_qf.&fp=917b53cc1ec39b52&q=Votifier+PHP+Encryption
Found this too: teamavolition (com)/topic/14380-solved-php-rsa-encryptions-votifier/
Best Regards,
- ImThatPedoBear
That's sorta a "naked" RSA public key. OpenSSL only works with public keys that are in an X.509 cert.
My recommendation would be to use phpseclib's Crypt_RSA. eg.
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('...'); // public key
$plaintext = '...';
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$ciphertext = $rsa->encrypt($plaintext);

PHPSecLIB Encrypt String and VB.NET Decrypt String

I am using RSA encryption with PHPSECLIB and VB.NET. The code for PHP is:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$key='-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----';
$rsa->loadKey($key); // public key
$plaintext = 'HELLO';
//$rsa->setEncryptionMode(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$rsa->paddable = false;
$ciphertext = $rsa->encrypt($plaintext);
echo base64_encode($ciphertext);
?>
VB.NET CODE:
Public Function DecryptText(ByVal Str As String) As String
Try
'Convert data to byte array
Dim Enc As Encoding = Encoding.UTF8
Dim dataToDecrypt() As Byte = Convert.FromBase64String(Str)
'Make our RSA Container
Dim RSA As New RSACryptoServiceProvider
'Import PRIVATE key into container
RSA.FromXmlString("<RSAKeyValue><Modulus>AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU+quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX/eP6yRnpS1b7m7T2Uc2yPq1DnWzVI+sIGR51s1/ROnQZswkPJHh71PThln</Modulus><Exponent>AQAB</Exponent><P>AN4DDp+IhBca6QEjh4xlm3iexzLajXYrJid6vdWmh4T42nar5nem8Ax39o3ND9b1Zoj41F9zFQmuZ8/AgabreKU=</P><Q>AMQi+R0G9m0K+AcqK3DFpv4RD9jGc0Tle98heNYT7EQvZuuiq4XjvRz0ybqN//bOafrKhsTpRS9DQ7eEpKLI4Bs=</Q><DP>FklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5kX6zk7S0ljKtt2jny2+00VsBerQ==</DP><DQ>AJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2eplU9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhM=</DQ><InverseQ>EaiK5KhKNp9SFXuLVwQalvzyHk0FhnNZcZnfuwnlCxb6wnKg117fEfy91eHNTt5PzYPpf+xzD1FnP7/qsIninQ==</InverseQ><D>Fijko56+qGyN8M0RVyaRAXz++xTqHBLh3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxE=</D></RSAKeyValue>")
'Decrypt the data
Dim decryptedData() As Byte = RSA.Decrypt(dataToDecrypt, False)
'Convert output byte array to a string
DecryptText = Enc.GetString(decryptedData)
Catch ex As Exception
Return ""
End Try
End Function
The problem that I am having is that everytime I copy the Base64 output from PHP and sub it on to the VB.NET DecryptText function, I get a blank results with the error "Bad Data". Can someone point me in the right direction here?
I strongly suspect $rsa->setEncryptionMode(CRYPT_RSA_PUBLIC_FORMAT_PKCS1); needs to be uncommented.
Also, $rsa->paddable = false... that's not doing anything. paddable isn't a variable that Crypt_RSA uses. Crypt_Base defines it but Crypt_RSA does not extend Crypt_Base.

Trouble with RSA using phpseclib in PHP

I'm trying to use the RSA implementation in phpseclib, I thought it would be easier to do the code once in a function and re-use the function.
When I've tried texting the code I get a error saying "decryption error"
Testing also made me realise that the ciphertext was different every time the code ran, so I'm clearly doing something wrong there!
The code for the functions is:
require_once "Crypt/RSA.php";
require_once "Crypt/AES.php";
//Function for encrypting with RSA
function rsa_encrypt($string, $public_key)
{
//Create an instance of the RSA cypher and load the key into it
$cipher = new Crypt_RSA();
$cipher->loadKey($public_key);
//Set the encryption mode
$cipher->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
//Return the encrypted version
return base64_encode($cipher->encrypt($string));
}
//Function for decrypting with RSA
function rsa_decrypt($string, $private_key)
{
//Create an instance of the RSA cypher and load the key into it
$cipher = new Crypt_RSA();
$cipher->loadKey($private_key);
//Set the encryption mode
$cipher->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
//Return the decrypted version
return $cipher->decrypt($string);
}
I've tried to test it using the following:
(The keys are just for testing so that's why its hardcoded).
It is in here that everytime the code is run that the value of $ciphertext changes everytime
//Private key
$private_key = "-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HKU0jQjX/n/db9vz/x0i3te/bK LNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJAHmbrNtrUB6ckrYLF75Y50nUN sBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQABAoGAGsiMtAyFu23ac0PdvOuhqm3O/vXAF0Ki zxwBVURfxM6LfiOOcRPe5RSKGTW+Cl7AQVEmMlsa/LtBhLhQ9LNQ5L/4oTmRhCGiZZEmccAdjKsx yMeaxkp+ZHvMxMKQNDgYg1CXqrCrpwwUuMUlA26tfxZ3xSFtFyDTaV9mgDQ1IGECQQCkX9Tum7D1 vQTwbhbYnu7eC4eUOaZeGWSEs2csK7U6vfZ3BzUZW/0tPqcSpQqcNxMtY9TiUsNRj1uM6jX3byp7 AkEA6Ab+wvOTNRtES77OAYG9gHGZZ+iXjQJ/6Z7JehN4p41UbDIf9nNUOLUPL9z5V1uOYnl1CWoo Cw95cdhKXxEAqQJBAIU5Or6tp250ZdVslM27ewSyuY9UblfkIsk/EscFIdzbbDAqwkmsefW6yvTc mU3lgYCPYlKRG8c19tCuX1ENY5MCQAz37x9YW975Ai01ofAFn2DheJCNOINCI4IcROiU1AaRaKmP d6fftFJjFFE5iZovXNr2LOt0yn4rxD7vtuBvY9kCQGyty6YCB6qaD7qXPMhLrLbGajAIWd6ETgxv frK/BJu+buPfDky/g1FhI5R9iMtL1xH0JYLJlaVocU+xSeA9DkY= -----END RSA PRIVATE KEY-----";
//Public key
$public_key = "-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HK U0jQjX/n/db9vz/x0i3te/bKLNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJA HmbrNtrUB6ckrYLF75Y50nUNsBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQAB -----END PUBLIC KEY-----";
//Test out the rsa encryption functions
$plaintext = "This is some plaintext to encrypt";
$ciphertext = rsa_encrypt($plaintext, $public_key);
$decipheredtext = rsa_decrypt($ciphertext, $private_key);
//Echo out results
echo sprintf("<h4>Plaintext for RSA encryption:</h4><p>%s</p><h4>After encryption:</h4><p>%s</p><h4>After decryption:</h4><p>%s</p>", $plaintext, $ciphertext, $decipheredtext);
EDIT:
Sample output is:
Plaintext for RSA encryption:
This is some plaintext we will encrypt
After encryption:
‘˜!ˆ_枦WýF¦E×9&ùš!´jéÓb÷á劀É7J+۪߯׎È㩨ɣ#(÷)ÃX„)÷O‘­Ë±N#Øv«ÓÌPƒ¹—Âî!a¢¦a&Á½Á˜ö‰ºŠCðJ«vW{uAåoOÂXäÞ#÷ï`agÏ:OŒ
After decryption:
//Nothing is returned, it is blank here
I think GigaWatt's answer is the correct one. As for this:
Testing also made me realise that the ciphertext was different every
time the code ran, so I'm clearly doing something wrong there!
PKCS#1 padding adds random bytes so the ciphertext's will always be different. The PKCS#1 algorithm however knows when the plaintext ends and the random bytes begin so it's able to separate the two and return you the result you're wanting.
EDIT: I got it to work after I replaced the spaces in your keys with new lines. eg.
$private_key = "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HKU0jQjX/n/db9vz/x0i3te/bK
LNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJAHmbrNtrUB6ckrYLF75Y50nUN
sBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQABAoGAGsiMtAyFu23ac0PdvOuhqm3O/vXAF0Ki
zxwBVURfxM6LfiOOcRPe5RSKGTW+Cl7AQVEmMlsa/LtBhLhQ9LNQ5L/4oTmRhCGiZZEmccAdjKsx
yMeaxkp+ZHvMxMKQNDgYg1CXqrCrpwwUuMUlA26tfxZ3xSFtFyDTaV9mgDQ1IGECQQCkX9Tum7D1
vQTwbhbYnu7eC4eUOaZeGWSEs2csK7U6vfZ3BzUZW/0tPqcSpQqcNxMtY9TiUsNRj1uM6jX3byp7
AkEA6Ab+wvOTNRtES77OAYG9gHGZZ+iXjQJ/6Z7JehN4p41UbDIf9nNUOLUPL9z5V1uOYnl1CWoo
Cw95cdhKXxEAqQJBAIU5Or6tp250ZdVslM27ewSyuY9UblfkIsk/EscFIdzbbDAqwkmsefW6yvTc
mU3lgYCPYlKRG8c19tCuX1ENY5MCQAz37x9YW975Ai01ofAFn2DheJCNOINCI4IcROiU1AaRaKmP
d6fftFJjFFE5iZovXNr2LOt0yn4rx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