I am using PHP to encrypt a string using a public key. I then pass the private key to a Node.js microservice for decryption. I am getting a successful decryption, but there is strange encoded characters before the true decrypted value.
PHP Generate Keys & Encrypt Value
$user_passphrase = '***'
$string = '123ABC';
// Generate key pair
$pkey = openssl_pkey_new([
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);
// Extract private key
openssl_pkey_export($pkey, $private_key, $user_passphrase);
// Base64 encode private key
$private_key = base64_encode($private_key);
// Extract public key
$pkey_details = openssl_pkey_get_details($pkey);
// Base64 encoded public key
$public_key = base64_encode($pkey_details['key']);
// Encrypt value
openssl_public_encrypt($string, $encrypted_value, base64_decode($public_key));
var_dump('Encrypted Value: ' . base64_encode($encrypted_value));
Node.js Decrypt Value
const crypto = require('crypto');
function decrypt (value, privateKey, passphrase) {
value = Buffer.from(value, 'base64');
privateKey = Buffer.from(privateKey, 'base64');
return crypto.privateDecrypt({
key: privateKey,
passphrase: passphrase,
padding: crypto.constants.RSA_NO_PADDING
}, value).toString('utf8');
}
const decryptedValue = decrypt(encryptedString, encryptedPrivateKey, userPassphrase);
console.log('Decrypted Value:' + decryptedValue);
When I run the php script, I pass the necessary values to the Node.js script. When the Node.js script decodes the value, the correct decoded value (123ABC) is at the end of a long string with strange encoding characters. Why am I seeing these strange characters?
�R^�z���p��LUZ��ϓ)�V'�5I��T�Z&jzD���TM�d��U�@��3�D�z�ו"��k��I��p���D�?����Oe���Ȯzl�Mss�L��;�j���yX�j�ŭ�]�� 123ABC