PHPSecLIB Encrypt String and VB.NET Decrypt String - php

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.

Related

RSA: generate public key from n and e in Python and PHP give me two different public key

In python, I extract modulus (n) and (e) from a public key like this:
#! /usr/bin/python3.5
# -*- coding: utf-8 -*-
import rsa
(pubkey, privkey) = rsa.newkeys(512)
dec_n = pubkey.n
dec_e = pubkey.e
In base64, the value of n and e are:
n:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIGqijUcytyQLcEVxC5gK4HDx7Y_c5aMJt9OOoWDfzcrifmZr0-8Q1i_LPE-4fuBLlaPl6EmgSN2wlbF_svHZV
e:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAB
And I have the following public key:
-----BEGIN RSA PUBLIC KEY-----
MEgCQQCIGqijUcytyQLcEVxC5gK4HDx7Y/c5aMJt9OOoWDfzcrifmZr0+8Q1i/LP
E+4fuBLlaPl6EmgSN2wlbF/svHZVAgMBAAE=
-----END RSA PUBLIC KEY-----
I tried to generate the same public key in PHP. To do this, I read this post: openssl: how can i get public key from modulus
So I wrote this code:
require_once("/var/www/phpseclib/Crypt/RSA.php");
$n = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIGqijUcytyQLcEVxC5gK4HDx7Y_c5aMJt9OOoWDfzcrifmZr0-8Q1i_LPE-4fuBLlaPl6EmgSN2wlbF_svHZV";
$e = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAB";
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64_decode(urldecode($n)), 256);
$exponent = new Math_BigInteger(base64_decode(urldecode($e)), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
$pub_key = $rsa->getPublicKey();
print_r($pub_key);
But I got this public key:
-----BEGIN PUBLIC KEY-----
MFgwDQYJKoZIhvcNAQEBBQADRwAwRAI9AIgaqKNRzK3JAtwRXELmArgcPHthzlowm3046hYN/NyuJ+ZmvTxDWIs8Th+4EuVo+XoSaBI3bCVsWy8dlQIDAQAB
-----END PUBLIC KEY-----
The difference is caused by two factors: First, the public key is displayed in the Python-code in the PKCS1-format ([1] and [2]), and in the PHP-code in the X.509-format ([1] and [3]). Secondly, there is a bug in the Base64-encoding.
Base64-encoding: In the Python-code the Base64url-encoding was used and in the PHP-code only the standard Base64-encoding ([4]). Although the code with the Base64url-encoding isn't posted, this can be concluded from the characters - and _ occurring in the encoded data. To use Base64url-decoding (instead of Base64-decoding) in the PHP-code:
$modulus = new Math_BigInteger(base64_decode(urldecode($n)), 256);
must be replaced by:
$modulus = new Math_BigInteger(base64url_decode(urldecode($n)), 256);
with ([5]):
function base64url_decode( $data ){
return base64_decode( strtr( $data, '-_', '+/') . str_repeat('=', 3 - ( 3 + strlen( $data )) % 4 ));
}
And analogously also for the exponent.
The PHP-code thus returns the following public key:
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIgaqKNRzK3JAtwRXELmArgcPHtj9zlo
wm3046hYN/NyuJ+ZmvT7xDWL8s8T7h+4EuVo+XoSaBI3bCVsX+y8dlUCAwEAAQ==
-----END PUBLIC KEY-----
Note: The Base64url-decoding of modulus and exponent is hexadecimal:
modulus : 0000000000000000000000000000000000000000000000000000000000000000881aa8a351ccadc902dc115c42e602b81c3c7b63f73968c26df4e3a85837f372b89f999af4fbc4358bf2cf13ee1fb812e568f97a126812376c256c5fecbc7655
exponent: 000000000000000000000000000000000000000000010001
The padding with the many 0-values isn't necessary (apart from the sign-byte), contains no information and only increases the amount of data.
Format: The public key from the last step is identical in content and only differs in the format (X.509). The easiest way to show this is to additionally display the public key in the PKCS1-format with ([6]):
$pub_key = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
print($pub_key . "\n");
The public key in the PKCS1-format matches the key of the Python-code. Another possibility is the direct comparison of both keys in an ASN.1 editor, e.g. online ([7]).
By the way: To use the public key of the Python-code also in the PHP-code, it isn't necessary to take the detour via modulus and exponent. This is much easier possible with ([6]):
$rsa = new Crypt_RSA();
$keydata = "-----BEGIN RSA PUBLIC KEY-----\n
MEgCQQCIGqijUcytyQLcEVxC5gK4HDx7Y/c5aMJt9OOoWDfzcrifmZr0+8Q1i/LP
E+4fuBLlaPl6EmgSN2wlbF/svHZVAgMBAAE=
\n-----END RSA PUBLIC KEY-----";
$rsa->loadKey($keydata);
$rsa->setPublicKey();
$pub_key = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
print($pub_key . "\n");
$pub_key = $rsa->getPublicKey();
print($pub_key . "\n");

RSA Decryption with phpseclib is failing

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;

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/?page=demo_rsa-encryption
keys:
$pub_key = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVd/gb2ORdLI7nTRHJR8C5EHs4
RkRBcQuQdHkZ6eq0xnV2f0hkWC8h0mYH/bmelb5ribwulMwzFkuktXoufqzoft6Q
6jLQRnkNJGRP6yA4bXqXfKYj1yeMusIPyIb3CTJT/gfZ40oli6szwu4DoFs66IZp
JLv4qxU9hqu6NtJ+8QIDAQAB
-----END PUBLIC KEY-----";
$priv_key = "-----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-----";
/*
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.

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

RSP encryption with my own key file

Ok so i am VERY new to cryptography
I want to encrypt a string using RSA. i have found many examples but most of them generate their own public/private keys or they use some other key format like pem/crt etc
I have my own public and private key file in the format of .key
Public key -> http://pastebin.com/hPT9LRCT
Private key-> http://pastebin.com/UYgJp8K7
How do i encrypt a string ("hello world") using my public key in php?
Could you show me an example or point me in the right direction?
thanks,
Vidhu
Try this (uses phpseclib, a pure PHP RSA implementation):
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArd+uKDi7g6cpmbotPre9KpFK4U1rM/FlEtHszIrMBmArLID4/uImes2L6K5sbKHbo3sIVdzFgrtB/ZdHTN11bM26OLpovCMs/HF3tqz93RMobdNv63IyOau4YgKZa+U2sW+1fGT1HtBesqGjlVlLZNJVR9ZETj4fuLKjNzOgegdbYFV9jIyP6JDi/9c6oyFRUI1anSWZcDFL+74Y4h4okAcbDgooczxBf3QlIJQdFVs9GOPCoIwmZ29c4VmBvESlRnjtXho/6sNQXlnLsG4v4GCzL7P1YOOf9FqV8XZuXJrEsTVJjDdYJdia6F3G/GRe+lRhReM42qlHqLKZpzjSFwIDAQAB'); // public key
$plaintext = 'hello world';
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);

Categories