我正在使用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
为空。有什么帮助吗?
答案 0 :(得分:0)
您在使用公钥/私钥时遇到一些问题。通过函数$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));
有关详细信息,请参阅documentation。
答案 1 :(得分:0)
如果加密模式未明确定义,则默认为OAEP。 OAEP要求密钥至少为2 *散列大小+ 2.默认散列phpseclib使用的是sha1,其长度为20个字节。所以密钥需要至少22个字节长或176位。
您的长度为16个字节或128位。
因此,您需要使用更大的密钥或更改加密模式以使用PKCS1填充。 PKCS1填充要求模数至少为11个字节。
如果所选模数的长度不足,当phpseclib显示错误时,它可能很有用。我会尝试向他提出建议。
此外,FWIW,教科书RSA没有规定任何最小长度要求,但phpseclib目前还没有实施教科书RSA。我想你可以通过直接调用_exponentiate来获得它,但这是唯一的方法。
教科书RSA很糟糕,因为它容易受到像PKCS1 / OAEP这样随机填充的某些类型的攻击。</ p>