简体   繁体   English

使用PhpSecLib和BouncyCastle的PHP和Java Decrpytion错误

[英]PHP & Java Decrpytion error using PhpSecLib and BouncyCastle

I'm trying to encrypt stuff in java using the public key generated by my PHP: 我正在尝试使用我的PHP生成的公钥来加密Java中的内容:

PHP Code 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));

For testing purposes, I've set aside a keypair (base64) of the above format. 为了进行测试,我保留了上述格式的密钥对(base64)。

I retrieve my Public Key in java and base64 decode it. 我在java中检索我的公钥,并对其进行解码。

    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);

I send the Base64 encrypted plaintext back to PHP for decryption using the following: 我使用以下命令将Base64加密的纯文本发送回PHP进行解密:

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

It's unable to decrpyt my encoded message and throws me the error: 它无法解密我的编码消息并抛出错误:

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

Can someone point me to the right direction? 有人可以指出我正确的方向吗? It's been hours since I'm trying to figure this out. 自从我试图弄清楚这已经过去了几个小时。

I'm using a hardcoded keypair so I guess there's no question of my keys being wrong... 我使用的是硬编码的密钥对,所以我想我的密钥是不对的……

To answer my own question: 要回答我自己的问题:

Everything apart from the final decryption PHP was correct. 除了最终的解密,PHP都是正确的。

It should be: 它应该是:

    $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));

I forgot to un-base64 my encrypted text sent from java and to set the encryption modes. 我忘记取消从Java发送的加密文本的base64设置设置加密模式。

Thanks neubert. 谢谢诺伊伯特。

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

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