使用带有phpseclib的十六进制编码公钥进行RSA加密
I am trying to encrypt a password to sent to through an API for authentication. From the API I can get the public key in this form:
{ "result": {
"keyId": "L5gslEaP921gEI34N5JRVRIEbbx78WJN",
"key": {
"n": "871db29fbb487b988f2d610d83a1e699c59473d73f6d38efa8d21645524b5fb549d5ffbc6d527b261ff2291cf3b3c81f25a4cb13c801d6f6eb3cae624d74724830f1cb45ec803d8836274f1ddea61ec25d5c44ad7ed0b8a56976291bd06abaa0beb9e1ecbbc59662d20f8ae71191e8cbe617acee2349a64aa20846d4d8910e53",
"e": "10001"
} } }
I need to encrypt a user password and send it back to the API. I am using PHP and this is what I have so far, but am not getting a proper hex encrypted password to send back:
$modulus = "871db29fbb487b988f2d610d83a1e699c59473d73f6d38efa8d21645524b5fb549d5ffbc6d527b261ff2291cf3b3c81f25a4cb13c801d6f6eb3cae624d74724830f1cb45ec803d8836274f1ddea61ec25d5c44ad7ed0b8a56976291bd06abaa0beb9e1ecbbc59662d20f8ae71191e8cbe617acee2349a64aa20846d4d8910e53";
$exponent = "10001";
$plaintext = "********";
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64_decode($modulus), 256);
$exponent = new Math_BigInteger(base64_decode($exponent), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;
How do I properly encode the password given the modulus and exponent from the API?
I figured out the solution. It is two parts.
Encode the hex to binary correctly using these two lines:
$modulus = new Math_BigInteger($modulus, 16);
$exponent = new Math_BigInteger($exponent, 16);
And out put the result as a bin to hex as Nate stated.
echo bin2hex($ciphertext);
It would be expected that the ciphertext is binary, not a hex string. A common way to convert it to a hex string is bin2hex()
.
Of course, this depends on what your API is expecting, but bin2hex()
would be a typical way to do it.
echo bin2hex($ciphertext);
And there’s the reverse function, hex2bin()
.
$modulus = "871db29fbb487b988f2d610d83a1e699c59473d73f6d38efa8d21645524b5fb549d5ffbc6d527b261ff2291cf3b3c81f25a4cb13c801d6f6eb3cae624d74724830f1cb45ec803d8836274f1ddea61ec25d5c44ad7ed0b8a56976291bd06abaa0beb9e1ecbbc59662d20f8ae71191e8cbe617acee2349a64aa20846d4d8910e53";
$exponent = "10001";
That's not base64 encoded. That's hex encoded. 10001 == 65537. Try to load your key like this:
$modulus = new Math_BigInteger(base64_decode($modulus), 16);
$exponent = new Math_BigInteger(base64_decode($exponent), 16);
eg. use 16 instead of 256 as the second parameter to the Math_BigInteger constructor.