我尝试使用PHPseclib加密和解密一个简单的字符串,但是当我尝试解密它时,结果为null或为空。有人可以帮帮我吗?
这是我的功能
public function myEncrypt($conteudoArquivo, $private_key) {
$rsa = new Crypt_RSA();
$rsa->loadKey($private_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$cipherText = base64_encode($rsa->encrypt($conteudoArquivo));
return $cipherText;
}
public function myDecrypt($cipherText, $public_key) {
$rsa = new Crypt_RSA();
$rsa->loadKey($public_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$plainText = base64_decode($rsa->decrypt($cipherText));
return $plainText;
}
,键值为:
$private_key = "-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQCRwpD+gV0skm+9SHPWFXAHkWV3r37I3N4fom45Z0imih3fDk9E Q6PuFb56Vfo8IWiNUoP6Gco/eDHcInzO1SSEn07reh86Aosnnj7m/RMg1N5k7A5C NH26YlATqgJe4DX8SdS/oKLit7xTo3aR+Wg3kZOQQmE5MyRq6TVDywhNyQIDAQAB AoGAVFk4mN75sUJogSu9RMURGIAOLM2U293ceIgBqxxW0XEZyiu4uTM/WRaiLJ82 eLeIjkeS8hccj9AZYl9exD5Zq7oGTH8HDQAcmZ6p0h3faI1/sR3gnqEB28GZJyd7 MsFRlRiOEdpJAki33m/6UsJ7hRHC6X/w2K4wofzmmHopOIECQQDCAMW7gc4Gmyb1 scP8OwA75QZWgeLo36d7ynUzjqoN682ckSbIxbT6z4eYhEKE/It0gt07WTNmrL0s vv4DH15xAkEAwFcTC1/FufpDvxt+EKnANmuH5ekri1zcsY3UMJJnjH9e7szfVTH6 JfhTRRSfi/oOe1aRinfcp/zMJhkf36VA2QJAO8K5JlWJ/Yb1rWGhGaWjINAf7637 E/kxQnTPPZ6Iy9kDcWNVKyub4FblUhoL06Nn4fAd7hZAOzSi4ZHD9XpIQQJAc1MC QTygcp1jB3A1i0oszLR23FyNVldMoE044BK4cZ5hTm+arRt1MFUPoIj4DNbW3g8O 3uZ1cGf8BA/mc5NDKQJAexm+LcJ3DOTaenQwHw77bfXhbvvCtcvAlYOIawkyDlTx AkBweqy8BEJbsVRSiBv7k6Hh+T+u1ZWaKDm/ZZCMkA== -----END RSA PRIVATE KEY----- "; $public_key = "-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HK U0jQjX/n/db9vz/x0i3te/bKLNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJA HmbrNtrUB6ckrYLF75Y50nUNsBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQAB -----END PUBLIC KEY-----";
答案 0 :(得分:3)
您需要使用公钥加密并使用私钥解密。这就是非对称加密的工作原理。在RSA"加密"使用私钥实际上是签名和"解密"用公钥验证签名。
另一件事是你没有正确反转Base64编码。所以你需要先解码然后解密:
$plainText = $rsa->decrypt(base64_decode($cipherText));
您提供的密钥不能与此代码一起使用,因为它们具有不同的模数。您可以这样生成密钥:
$rsa = new Crypt_RSA();
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$keys = $rsa->createKey(2048);
$private_key = $keys["privatekey"];
$public_key = $keys["publickey"];