我正在尝试使用 Cipher cipher = Cipher.getInstance("RSA");
以及 PHP 和 phpseclib 重现 Java 加密。
我尝试了这个和很多东西,但似乎数据没有正确加密
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->loadKey($pub_key);
$ciphertext = $rsa->encrypt($plaintext);
我尝试了不同的组合,例如
$rsa->setMGFHash('sha512');
$rsa->setHash('sha512');
//$rsa->setMGFHash('sha256');
//$rsa->setHash('sha256');
没有成功。
我错过了什么吗?
最佳答案
永远不要使用像这样的不完整的密码字符串:
Cipher cipher = Cipher.getInstance("RSA");
这不指定填充,因此取决于默认安全提供程序首选的填充。这可能默认为:
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
这将兼容
$rsa = new Crypt_RSA();
$rsa->loadKey($pub_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
但是您不应该再使用 PKCS#1 v1.5 填充。您确实应该使用 OAEP (meaning):
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
而 phpseclib 的等价物应该是
$rsa = new Crypt_RSA();
$rsa->loadKey($pub_ley);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->setHash('sha256');
$ciphertext = $rsa->encrypt($plaintext);
关于java - Phpseclib 相当于 Java RSA 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34187124/