2010-04-09 156 views
9

在PHP我RSA加密消息由.NET应用程序进行解密...但我不断收到来自.NET“坏钥匙”例外....RSA加密在PHP中解密.NET

对于RSA加密,我使用PEAR类Crypt_RSA->使用公钥加密(这是一个模数,指数对),我在.NET中使用加密系统...

我想最简单的问题是 - >“Bad Key”是否意味着它无法解密该消息? IE,它没有正确加密?

更难的问题是 - 是否有任何关于RSA加密的具体内容导致.NET和PHP之间的怪癖?

+1

请问密钥本身有问题吗?奇怪的字符,UNICODE和UTF-8之间的问题? – 2010-04-09 15:11:02

+0

您可能会使用不同的填充。 – SLaks 2010-04-09 15:11:37

+0

RE:填充:关于字符串本身?在这种情况下,它正好是32个字节 - 可以被8整除......所以我有这个覆盖了吗? – user312904 2010-04-09 15:17:30

回答

3

PEAR上的Crypt_RSA不使用PKCS#1编码。我怀疑这就是为什么.NET给你一个错误信息。

print $rsa_obj->encryptBinary("1234567", $key_pair->getPublicKey()); 

以的,输出和管道它:

由于它打破的一个例子,使用我到Crypt_RSA加密字符串“1234567”(我将跳过表示密钥加载)创建的PHP脚本通过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: 

OpenSSL的预计PKCS#1填充默认,但加入-raw(没有填充)标志OpenSSL的也没有帮助。

使用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"; 
} 

而且在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"; 
} 

证书的背景下,的RSA是X.509证书,它们是RSA密钥以及有关这些密钥的数据。 X.509证书用于SSL,但不要求使用RSA。

14

Security Warning: Use OAEP, not PKCS#1 .

如果您想要使用不需要openssl扩展名的解决方案,请尝试使用phpseclib的Crypt_RSA。例子如下:

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')); 
?> 

加密与PKCS:

与PKCS#1填充解密#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'); 
?> 

OpenSSL的rsautl -inkey privatekey.tx吨-decrypt -in ciphertext.txt -out plaintext.txt

解密与OAEP填充:

OpenSSL的rsautl -inkey privatekey.txt -encrypt -oaep -in plaintext.txt -out密文。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')); 
?> 

加密与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'); 
?> 

OpenSSL的rsautl -inkey privatekey.txt -decrypt -oaep -in ciphertext.txt -out plaintext.txt

phpseclib可以是从http://phpseclib.sourceforge.net/下载

祝你好运!

+0

这很好,但我会强烈推荐OAEP,并且由于填充oracle攻击而从不使用PKCS1填充。 – 2015-12-03 05:41:16