There is a payment gateway that I'm working on, and they have a Java demo that is working however I want to implement this in php instead.
The payment gateway encrypt the payload by using 3DES with a random generated key. That key was encrypted with RSA by using the payment gateway's PUBLIC key.
The problem is when I use the php script to do RSA encryption on that key, the payment gateway isn't can't extract the key correctly and apparently the RSA encryption on the PHP wasn't working correctly...
Here's the Java version of the RSA encryption:
public static byte[] encrypt(byte[] data, String pubKey64) {
try {
byte[] key = Toolkit.base64Decode(pubKey64);
KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key);
RSAPublicKey pbk = (RSAPublicKey) rsaKeyFac.generatePublic(keySpec);
System.out.println("MODE:"+Cipher.ENCRYPT_MODE);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, pbk);
byte[] encDate = cipher.doFinal(data);
return encDate;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
And here what's I came out with at the PHP script:
use phpseclib\Crypt\RSA as RSA;
$PUB_KEY = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJ1fKGMV/yOUnY1ysFCk0yPP4bfOolC/nTAyHmoser+1yzeLtyYsfitYonFIsXBKoAYwSAhNE+ZSdXZs4A5zt4EKoU+T3IoByCoKgvpCuOx8rgIAqC3O/95pGb9n6rKHR2sz5EPT0aBUUDAB2FJYjA9Sy+kURxa52EOtRKolSmEwIDAQAB
-----END PUBLIC KEY-----';
$PAYLOAD = 'b78850d2f35108b4bc4e7a41';
function encrypt($key,$payload){
$rsa = new RSA();
$rsa->loadKey($key); // public key
$rsa->setEncryptionMode(2);
$ciphertext = $rsa->encrypt($payload);
return base64_encode($ciphertext);
}
The Java version was using PKCSPADDING so I set the mode on phpseclib to 2 which is PKCSPADDING but still it won't work. Am I missing anything? Can anyone please point it out for me?
UPDATE:
Not sure if this is the reason that causing it but I removed the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY ----" portion and it worked.
Thanks for everyone's help.
Try doing
define('CRYPT_RSA_PKCS15_COMPAT', true);
before you start the encryption process.Quoting phpseclib 2.0's RSA.php: