繁体   English   中英

Java中的RSA加密,PHP中的解密

[英]RSA encryption in Java, decryption in PHP

我正在尝试使用 Android 应用程序中的 RSA 公钥加密 AES 密钥,然后使用带有 phpseclib 的 PHP 在服务器上解密 AES 密钥。 我已经测试了通过加密 static 文本并在之后对其进行解密以检查我是否仍然得到原始文本,以确保 RSA 加密/解密在两个平台上都能正常工作。 根据测试,RSA 代码在每个平台上单独工作,但平台之间似乎存在差异。

在 Java 中,我正在使用 Bouncy Castle 库并具有以下代码:

RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
new BigInteger("00c897f9e401819e223ffbecc6f715a8d84dce9022762e0e2d54fa434787fcaf230d28bd0c3b6b39b5211f74ffc4871c421362ccfc07ae98b88fa9728f1e26b8210ebbf4981e45867fe810938294d0095d341b646b86dcbd4c246676c203cb1584d01eef0635299714d94fa12933ecd35e6c412573156d9e6e549b7804eb6e165660507d8748bcc8c60da10099bacb94d3f7b50b1883ee108489e0dd97ed7d28e564edd4ee5d6b4225f5c23cdaaf495c3fa08c3b82e1674946e4fa1e79b2493204d6953c261105ba5d0f8dcf3fcd39a51fbc18a5f58ffff169b1bed7ceeded2ae0e8e8e2238e8b77b324d1a482593b1a642e688c860e90d5a3de8515caf384133b", 16),
new BigInteger("11", 16));
keyFactory = KeyFactory.getInstance("RSA", "BC");
//RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec(rsaKey.MODULUS, new BigInteger("11", 16));
RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);  

//Set up the cipher to RSA encryption
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);

// make sure the Aes Key is less than a block size
// otherwise major errors will occur
if(AesKey.length * 8 > pubKey.getModulus().bitLength())
    return "Error: AesKey bigger than block size of RSA Key";

byte[] encryptedKey = cipher.doFinal(AesKey);

// return result Base64 encoded
return Base64.encodeToString(encryptedKey, Base64.DEFAULT);

然后在 PHP 中,我使用以下代码来解密 AES 密钥:

$AESkey = base64_decode($AES);

$rsa = new Crypt_RSA();
$private = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/PrivateData/private_key.pem');
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->loadKey($private);
$AESkey = $rsa->decrypt($AESkey);

When the AES key is being decrypted by the server, I always get the following error: Decryption error in C:\xampp\php\PEAR\phpseclib\Crypt\RSA.php on line 1911. Looking at the code in RSA.php,我认为该错误与加密期间不正确的填充有关,但我似乎无法找到修复它的方法。

更新:我发现上面的加密/解密代码实际上是正确的。 我遇到的问题是,在将数据从应用程序发送到 php 之前,我没有对 output 进行编码,因此一些信息丢失了。

您使用的是哪个版本的 phpseclib? 根据版本,以下可能有所帮助:

http://www.frostjedi.com/phpbb/viewtopic.php?p=118414#p118414

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM