我使用phpseclib
进行RSA
加密http://phpseclib.sourceforge.net/.
这是我的php代码:
include('Math/BigInteger.php');
include('Crypt/RSA.php');
$message="123456";
$private_modulus = "272435F22706FA96DE26E980D22DFF67";
$private_exponent = "158753FF2AF4D1E5BBAB574D5AE6B54D";
$rsa = new Crypt_RSA();
$message = new Math_BigInteger(base64_decode($message), 256);
$private_modulus = new Math_BigInteger(base64_decode($private_modulus), 256);
$private_exponent = new Math_BigInteger(base64_decode($private_exponent), 256);
$rsa->loadKey(array('n' => $private_modulus, 'e' => $private_exponent));
$encryptedText=$rsa->encrypt($message);
echo $encryptedText;
但是,encryptedText
为空。有什么帮助吗?
您的公钥/私钥有一些问题。从函数$rsa->loadKey()
注释的外观来看,第一个参数是字符串,但您分配了一些奇怪的数组。。。
/**
* Loads a public or private key
*
* Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
*
* @access public
* @param String $key
* @param Integer $type optional
*/
function loadKey($key, $type = false)
使用随机公钥/私钥进行加密/解密的示例:
include('_seclib/Math/BigInteger.php');
include('_seclib/Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey());
# encrypt
$message = '123456';
$rsa->loadKey($publickey);
$ciphertext = $rsa->encrypt($message);
var_dump($ciphertext);
# decrypt
$rsa->loadKey($privatekey);
var_dump($rsa->decrypt($ciphertext));
有关详细信息,请参阅文档。
如果未明确定义加密模式,则默认为OAEP。OAEP要求密钥至少为2*哈希大小+2。phpseclib使用的默认哈希是sha1,其长度为20字节。因此,密钥至少需要22字节长或176位。
您的长度为16字节或128位。
因此,您要么需要使用更大的密钥,要么更改加密模式以使用PKCS1填充。PKCS1填充要求模至少为11个字节。
如果phpseclib在所选模的长度不足时显示错误,这可能会很有用。我会尽量向他建议的。
此外,FWIW,教科书RSA没有强加任何最小长度要求,但phpseclib目前还没有实现教科书RSA。我想你可以直接调用_exponentiate来获得它,但这是唯一的方法。
教科书中的RSA很糟糕,因为它容易受到某些类型的攻击,而PKCS1/OAEP等随机填充可以抵御这些攻击。