问题
Hi I would like to know why RSA can be performed (encrypt/decrypt) with only one public key in phpseclib?
$rsa is an instance of phpseclib/Crypt/RSA.php (link: https://github.com/phpseclib/phpseclib/blob/master/phpseclib/Crypt/RSA.php) $publicKey keys here are the same.
function encryptData($data, $publicKey) {
$rsa = new Crypt_RSA();
$rsa->loadKey($publicKey); // public key
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$output = $rsa->encrypt($data);
return base64_encode($output);
}
function decryptData($data, $publicKey) {
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = base64_decode($data);
$rsa->loadKey($publicKey); // public key
$output = $rsa->decrypt($ciphertext);
// $output = $rsa->decrypt($data);
I don't understand why the above code works. And for the same reason, I can't implement it in Ruby which requires a key pair for such operation. Any help would be appreciate.
回答1:
In it's most basic form all you need for an RSA key, be it public or private, is an exponent and a modulo. In practice, private keys often have additional parameters to speed up computation via the Chinese Remainder Theorem, but in practice, they don't need that.
So in RSA's most basic form, a public and private key are indistinguishable from one another.
That said, you still gotta have both if you want to encrypt / decrypt.
I don't understand why the above code works.
It doesn't work. Not like you seem to be expecting it to.
Well, right now, it doesn't actually even do anything. You just have an encrypt and decrypt function but aren't passing it any parameters and are just presupposing it works with the same key for both. But it doesn't as the following demonstrates:
<?php
include('Crypt/RSA.php');
function encryptData($data, $publicKey) {
$rsa = new Crypt_RSA();
$rsa->loadKey($publicKey); // public key
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$output = $rsa->encrypt($data);
return base64_encode($output);
}
function decryptData($data, $publicKey) {
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = base64_decode($data);
$rsa->loadKey($publicKey); // public key
$output = $rsa->decrypt($ciphertext);
// $output = $rsa->decrypt($data);
return $output;
}
$rsa = new Crypt_RSA();
extract($rsa->createKey());
$ciphertext = encryptData('zzz', $publickey);
echo decryptData($ciphertext, $publickey);
That yields a decryption error.
Now, if you replace that last line with this:
echo decryptData($ciphertext, $privatekey);
Do that and you'll get the original text back. But you have to use the private key to get that text back - not the public key.
来源:https://stackoverflow.com/questions/51929780/phpseclib-decrypt-and-encrypt-data-with-only-public-key