Server Side RSA Encryption script example doesn't produce the correct code

#1

https://docs.juce.com/master/classRSAKey.html
The example for the server php script is slightly wrong. It should be

function applyToValue ($message, $key_part1, $key_part2)
{
$result = new Math_BigInteger();
$zero = new Math_BigInteger();
$value = new Math_BigInteger (strrev($message) ,256);
$part1 = new Math_BigInteger ($key_part1, 16);
$part2 = new Math_BigInteger ($key_part2, 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());
}

There should be no strrev of the return value. Just FYI.

0 Likes

#2

We had some problems embedding the results of this code into a JSON response from server due to some character encoding issue.
The final code we used was:

include ('Math/BigInteger.php');  // get this from: phpseclib.sourceforge.net
function applyToValue ($message, $key_part1, $key_part2)
{
    $result = new Math_BigInteger();
    $zero  = new Math_BigInteger();
    $value = new Math_BigInteger (strrev ($message), 256);
    $part1 = new Math_BigInteger ($key_part1, 16);
    $part2 = new Math_BigInteger ($key_part2, 16);
    while (! $value->equals ($zero))
    {
        $result = $result->multiply ($part2);
        list ($value, $remainder) = $value->divide ($part2);
        $result = $result->add ($remainder->modPow ($part1, $part2));
    }
    return $result->toHex();
}

which allows us to successfully decode the result in the client with:

    RSAKey publicKey("<public key>");

    BigInteger val;
    val.parseString("<hex result from JSON>", 16);

    publicKey.applyToValue(val);

    const MemoryBlock mb(val.toMemoryBlock());
    std::cout << mb.toString() << std::endl;
1 Like

#3

Thanks, I’ll get the docs updated.

0 Likes