Encrypt RSA on PHP server

Hey all,
I try to encrypt a little JSON file (170 bytes) with the PHP snippet that is found here on the forum as well as on the Docs of RSAKey.

Minor adjustment: I used explode to split the string I got from RSAKey.toString() at the comma.
Other adjustment: Return as toBytes() and use base64_encode to send it back.

require ('phpseclib/Math/BigInteger.php');

function rsa_encode($message, $key)
{
    $key_parts = explode (",", $key);
    $result = new Math_BigInteger();
    $zero  = new Math_BigInteger();
    $value = new Math_BigInteger (strrev ($message), 256);
    $part1 = new Math_BigInteger ($key_parts[0], 16);
    $part2 = new Math_BigInteger ($key_parts[1], 16);

    while (! $value->equals ($zero))
    {
        $result = $result->multiply ($part2);
        list ($value, $remainder) = $value->divide ($part2);
        $result = $result->add ($remainder->modPow ($part1, $part2));
    }
    return ($result->toBytes());
}

However, I get garbage when trying to decrypt. The same code decrypting when encoded with juce works fine.

Has anyone an idea what to try to debug or spots an error I made?

Thanks for all hints or shots in the dark…

1 Like

Hi Daniel, try toHex() instead of toBytes() at the end.

2 Likes

Ok, I wanted to pack the binary blob into base64 to be as close to any standard as possible.
However, when I use toHex() and load it in the juce client with BigInteger.parseFromString(data, 16), it works out of the box.

I guess I will live with the hex string…

Thanks a ton, @AdamVenn !

The problem might have been in the base64 decoding on the client side. I remember that JUCE had a non-standard base64-like encoding prior to adding the support for the standard Base64. Perhaps you were using the non-standard one for decoding?

I had that problem before, so I was sure to choose the standard one in juce::Base64::convertFromBase64().
I also checked to have the stream deleted before reading, another pitfall of that interface.

My hunch is, that the PHP and the toByte does something wrong… When it takes the hex string, two characters form one byte… Maybe there is some endianess or direction of the hex stream going on?

Oh, and I had removed the RSA encode for testing, but stuff the json into the Base64, so that can be ruled out.

1 Like

Happy I could return the favour :slight_smile: