簡體   English   中英

使用PhpSecLib和BouncyCastle的PHP和Java Decrpytion錯誤

[英]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中檢索我的公鑰,並對其進行解碼。

    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設置設置加密模式。

謝謝諾伊伯特。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM