I am trying to figure out an issue with a PHP script I'm writing. Essentially, this script is using the phpseclib library to encrypt a password using a public RSA key passed to it by a ASP.NET application. The password seems to be getting encrypted fine, but when I attempt to put the encrypted string into an json string, it gets turned into NULL.
Code:
// Create our RSA encryption object
$rsa = new Crypt_RSA();
// Get modulus and exponent for our public key
// ($keyInner was gathered from the keygen server)
$modulus = new Math_BigInteger(base64_decode($keyInner->{'Modulus'}), 256);
$exponent = new Math_BigInteger(base64_decode($keyInner->{'Exponent'}), 256);
// Generate our public key and padding scheme
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
// Gather user data
// In reality this is gathered from a form but for
// example's sake I'll be using static values
$username = 'foo';
$password = 'boo';
// Encrypt password
$password = $rsa->encrypt($password);
// $password == <some encrypted string>
// gettype($password) == string
// mb_detect_encoding == UTF_8
// Create json
$arr = json_encode(array(
'payload' => array(
'username' => $username,
'password' => $password,
)
));
// $arr = {"payload":{"username":"Bob","password":null}}
It sounds like the data is not UTF-8 valid so it fails to encode.
You can use json_last_error to detect what the actual problem is if $arr returns null.
json_encode
doesn't work well with binary data, you'd be better off base64_encode
ing it:
// Create json
$arr = json_encode(array(
'payload' => array(
'username' => $username,
'password' => base64_encode($password),
)
));
And then decode it on the recieving end.