小智 14
安全警告:使用OAEP,而不是PKCS#1.
如果您想使用不需要openssl扩展的解决方案,请尝试使用phpseclib的Crypt_RSA.示例如下:
用PKCS#1填充解密:
openssl rsautl -inkey privatekey.txt -encrypt -in plaintext.txt -out ciphertext.txt
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('privatekey.txt'));
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo $rsa->decrypt(file_get_contents('ciphertext.txt'));
?>
Run Code Online (Sandbox Code Playgroud)
使用PKCS#1填充加密:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('privatekey.txt'));
$rsa->loadKey($rsa->getPublicKey());
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo $rsa->encrypt('1234567890');
?>
Run Code Online (Sandbox Code Playgroud)
openssl rsautl -inkey privatekey.txt -decrypt -in ciphertext.txt -out plaintext.txt
使用OAEP填充解密:
openssl rsautl -inkey privatekey.txt -encrypt -oaep -in plaintext.txt -out ciphertext.txt
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('privatekey.txt'));
echo $rsa->decrypt(file_get_contents('ciphertext.txt'));
?>
Run Code Online (Sandbox Code Playgroud)
使用OAEP填充加密:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents('privatekey.txt'));
$rsa->loadKey($rsa->getPublicKey());
echo $rsa->encrypt('1234567890');
?>
Run Code Online (Sandbox Code Playgroud)
openssl rsautl -inkey privatekey.txt -decrypt -oaep -in ciphertext.txt -out plaintext.txt
phpseclib可以从http://phpseclib.sourceforge.net/下载
祝好运!
PEAR 上的 Crypt_RSA 不使用 PKCS#1 编码。我怀疑这就是 .NET 向您提供错误消息的原因。
作为破坏的一个例子,我使用 Crypt_RSA 创建了一个 php 脚本来加密字符串“1234567”(我将跳过显示密钥加载):
print $rsa_obj->encryptBinary("1234567", $key_pair->getPublicKey());
Run Code Online (Sandbox Code Playgroud)
获取该输出并通过 openssl 命令行工具进行管道传输会出现以下错误:
$ ./crypt | openssl rsautl -inkey privkey.pem -decrypt
RSA operation error
18437:error:04065084:rsa routines:RSA_EAY_PRIVATE_DECRYPT:data too large for modulus:fips_rsa_eay.c:558:
Run Code Online (Sandbox Code Playgroud)
openssl 默认情况下期望 PKCS#1 填充,但向 openssl 添加 -raw (无填充)标志也没有帮助。
在 php 中使用 openssl 扩展可以提供适当的填充(默认为 PKCS#1,其他可用):
$pem = file_get_contents("pubkey.pem");
$key = openssl_pkey_get_public($pem);
$encrypted = "";
if(openssl_public_encrypt("1234567", $encrypted, $key)) {
print $encrypted;
} else {
print "failed\n";
}
Run Code Online (Sandbox Code Playgroud)
以及php中的解密代码:
$pem = file_get_contents("privkey.pem");
$key = openssl_pkey_get_private($pem);
$enc_data = file_get_contents("openssl.crypted");
$decrypted = "";
if(openssl_private_decrypt($enc_data, $decrypted, $key)) {
print "$decrypted\n";
} else {
print "failed\n";
}
Run Code Online (Sandbox Code Playgroud)
RSA 上下文中的证书是 X.509 证书,它是 RSA 密钥加上有关这些密钥的数据。X.509 证书用于 SSL,但不需要使用 RSA。