PHP&;使用PhpSecLib和BouncyCastle的Java解密错误


PHP & Java Decrpytion error using PhpSecLib and BouncyCastle

我正试图使用我的PHP:生成的公钥来加密java中的内容

PHP代码

    $rsa = new Crypt_RSA();
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
    $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);

    $keys = $rsa->createKey(1024);
    extract($keys);
    echo (base64_encode($publickey));

出于测试目的,我留出了一个以上格式的密钥对(base64)。

我在java中检索我的公钥,并对其进行base64解码。

    String publicKeyDecoded = new String(Base64.decode(publicKey));
    PEMParser pr = new PEMParser(new StringReader(publicKeyDecoded));
    Object obj = pr.readObject();
    pr.close();
    SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) obj;
    AsymmetricKeyParameter askp = PublicKeyFactory.createKey(spki);
    AsymmetricBlockCipher e = new RSAEngine();
    e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
    e.init(true, askp);
    byte[] messageBytes = plainText.getBytes();
    byte[] encryptedData = e.processBlock(messageBytes, 0, messageBytes.length);
    byte[] encryptedDataBase = Base64.encode(encryptedData);

我使用以下方法将Base64加密的明文发送回PHP进行解密:

    $rsa->loadKey($privatekey) or die ("Cant load");
    echo $rsa->decrypt($cipher);        

它无法解密我的编码消息,并向我抛出错误:

    Decryption error in <b>/opt/lampp/htdocs/Crypt/RSA.php</b> on line <b>2120</b>

有人能给我指正确的方向吗?我已经好几个小时没有想清楚了。

我使用的是硬编码的键盘,所以我想我的钥匙肯定是错的。。。

回答我自己的问题:

除了最后的解密PHP之外,所有的东西都是正确的。

应该是:

    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
    $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
    $rsa->loadKey(base64_decode($_SESSION['private'])) or die ("Cant load");
    echo $rsa->decrypt(base64_decode($cipher));

我忘了打开从java发送的加密文本的base64并设置加密模式。

谢谢纽伯特。