What's the PHP equivalent of Java RSA Decryption?

364 views Asked by At

What I'm trying to do here is implement Samsung Pay on PHP but so far I haven't been able to get the decryption process correctly.

Below is the Java code sample that I'm trying to port in PHP:


import java.io.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import javax.crypto.*;

public static void main(String[] args) {
    String encPayload = {{encryptedPayload}};
    String privateKeyFilePath = "./rsapriv.pem";
    getDecryptedData(encPayload, privateKeyFilePath);
}

public static String getDecryptedData(String encPayload, String privateKeyFilePath) {
    String delims = "[.]";
    String[] tokens = encPayload.split(delims);
    Decoder urlDecoder = Base64.getUrlDecoder();
    byte[] encKey = urlDecoder.decode(tokens[1]);
    byte[] iv = urlDecoder.decode(tokens[2]);
    byte[] cipherText = urlDecoder.decode(tokens[3]);
    byte[] tag = urlDecoder.decode(tokens[4]);
    byte[] plainText = new byte[cipherText.length];
    try {
// Read private key file
        File privateKeyFile = new File(privateKeyFilePath);
        DataInputStream dis = new DataInputStream(new FileInputStream(privateKeyFile));
        byte[] privKeyBytes = new byte[(int) privateKeyFile.length()];
        dis.read(privKeyBytes);
        dis.close();
// Set private key spec
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privKey = keyFactory.generatePrivate(spec);
        Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        decryptCipher.init(Cipher.DECRYPT_MODE, privKey);
        byte[] plainEncKey = decryptCipher.doFinal(encKey);
        final Cipher aes128Cipher = Cipher.getInstance("AES/GCM/NoPadding");
        final GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(16 * Byte.SIZE, iv);
        final SecretKeySpec keySpec = new SecretKeySpec(plainEncKey, "AES");
        aes128Cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
        int offset = aes128Cipher.update(cipherText, 0, cipherText.length, plainText, 0);
        aes128Cipher.update(tag, 0, tag.length, plainText, offset);
        aes128Cipher.doFinal(plainText, offset);
    } catch (Exception e) {
    }
    return new String(plainText);
}

And here's what I have tried so far in PHP:

    private function getDecryptedData($encPayload, $privateKeyFilePath) {
        // Split the base64 encoded url
        $tokens = explode('.', $encPayload);

        // Convert to bytes
        $header = base64_decode($tokens[0]);
        $encKey = base64_decode($tokens[1]);
        $iv = base64_decode($tokens[2]);
        $cipherText = base64_decode($tokens[3]);
        $tag = base64_decode($tokens[4]);
        $plainText = "";

        try {
            $private = RSA::loadPrivateKeyFormat('PKCS8', $privateKeyFilePath)->withPadding(RSA::ENCRYPTION_PKCS1);
            dd($private->decrypt($encKey));

           // then some AES-128 GCM Stuff.

        } catch (\Exception $ex) {
            dd($ex->getMessage());
        }
    }

I'm supposed to get a plaintext but instead I'm getting a Decryption error message, which is making me think if whether I'm doing it the right way or not.

UPDATE: The previous syntax used was phpseclib v2.0 but now I've changed the syntax to phpseclib v3.0

1

There are 1 answers

0
neubert On

From your PHP code:

$private = RSA::loadPrivateKeyFormat('PKCS8', $privateKeyFilePath)
    ->withPadding(RSA::ENCRYPTION_PKCS1);

It doesn't read the key from the filesystem - it reads the key as a string. So you prob need to do this:

$private = RSA::loadPrivateKeyFormat('PKCS8', file_get_contents($privateKeyFilePath))
    ->withPadding(RSA::ENCRYPTION_PKCS1);

Also, for good measure, I'd just do this, instead:

$private = PublicKeyLoader::load(file_get_contents($privateKeyFilePath))
    ->withPadding(RSA::ENCRYPTION_PKCS1);

phpseclib will auto detect the key format so might as well take advantage of that.

For more info see https://phpseclib.com/docs/java