2

I'm trying to reproduce Java encryption using Cipher cipher = Cipher.getInstance("RSA"); with PHP and phpseclib.

I tried this and so many things, but it seems the data are not correctly encrypted

$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->loadKey($pub_key);
$ciphertext = $rsa->encrypt($plaintext);

I tried different combination like

$rsa->setMGFHash('sha512');
$rsa->setHash('sha512');
//$rsa->setMGFHash('sha256');
//$rsa->setHash('sha256');

without success.

Am I missing something?

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
Kevlys
  • 136
  • 1
  • 10

1 Answers1

3

Don't ever use incomplete Cipher strings like this one:

Cipher cipher = Cipher.getInstance("RSA");

This doesn't specify the padding and therefore depends on which padding the default security provider prefers. This will probably default to:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

This would be compatible to

$rsa = new Crypt_RSA();
$rsa->loadKey($pub_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);

But you shouldn't use PKCS#1 v1.5 padding anymore. You really should be using OAEP (meaning):

Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");

and the phpseclib equivalent should be

$rsa = new Crypt_RSA();
$rsa->loadKey($pub_ley);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setHash('sha256');
$ciphertext = $rsa->encrypt($plaintext);
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Thanks for your reply, unfortunately, I don't have access to the Java code :/. I already tried with `CRYPT_RSA_ENCRYPTION_PKCS1`, without success anymore. – Kevlys Dec 10 '15 at 08:55
  • When I try with `CRYPT_RSA_ENCRYPTION_PKCS1`, the `$ciphertext` is already the same, whereas the Java code produces a different key each time. I suppose that the ` Cipher.getInstance("RSA");` is using OAEP ? – Kevlys Dec 10 '15 at 09:05
  • 1
    Paddings are usually randomized. There is a type 1 variant of PKCS#1 v1.5 padding that doesn't use randomization, so each ciphertext will be the same for the same key and plaintext. If you want to check compatibility between randomized versions then you need to encrypt in Java and decrypt in PHP and vice versa. – Artjom B. Dec 10 '15 at 09:55