带有 phpseclib 的 RSA 和 AES 混合 encryption/decryption 失败

RSA and AES hybrid encryption/decryption with phpseclib fails

我想使用非对称密钥加密和解密字符串。

由于字符串可以更大,我决定尝试这样的混合解决方案:

<?php

use phpseclib\Crypt\RSA;
use phpseclib\Crypt\Rijndael;
use phpseclib\Crypt\Random;


function generateKeys()
{
    $rsa = new RSA();

    return $rsa->createKey();
}

function encrypt($plaintext, $asym_key, $key_length = 150)
{
    $rsa = new RSA();
    $rij = new Rijndael();

    $sym_key = Random::string($key_length);

    $rij->setKey($sym_key);
    $ciphertext = $rij->encrypt($plaintext);
    $ciphertext = base64_encode($ciphertext);

    $rsa->loadKey($asym_key);
    $sym_key = $rsa->encrypt($sym_key);

    $sym_key = base64_encode($sym_key);
    $len     = strlen($sym_key);

    $len
         = dechex($len);
    $len = str_pad($len, 3, '0', STR_PAD_LEFT);

    $message = $len.$sym_key.$ciphertext;

    return $message;
}

function decrypt($message, $asym_key)
{
    $rsa = new RSA();
    $rij = new Rijndael();

    $len     = substr($message, 0, 3);
    $len     = hexdec($len);
    $sym_key = substr($message, 0, $len);

    $message    = substr($message, 3);
    $ciphertext = substr($message, $len);
    $ciphertext = base64_decode($ciphertext);

    $rsa->loadKey($asym_key);
    $sym_key = base64_decode($sym_key);
    $sym_key = $rsa->decrypt($sym_key);

    // Decrypt the message
    $rij->setKey($sym_key);
    $plaintext = $rij->decrypt($ciphertext);

    return $plaintext;
}

$keys      = generateKeys();
$encrypted = encrypt('test', $keys['publickey']);

print_r($encrypted);

$decrypted = decrypt($encrypted, $keys['privatekey']);

print_r($decrypted);

这是我第一次尝试的结果:

Public键

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDsH0CaSboYlkKGRvdHxa45649H
65I41SQtsRxfYDuJ2IFIcpTPgV/bEj+V/tLVL2HagMixB9v7J9E+HVmvXkhEVM/F
h5dc404/XID4LLvrasrdh3RfPpEWZm0afT7Vt4TXx8nv0gWU/8G2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RBv5sbjHgJkhUDcbM9P/zrQLuP0Qq+wLPfxa1yE907DvXJ4dRUJVJF9F+esi51ucQMU5GYQS48ThlmBvh69zUCf0NX6s9k5cCzGT42RW7hF3yHEwcr9lOZLAhq1tn9Z8qM0pNrUdHAcB6N2Hv5qDbr/rFw9fX0vKts8DM782ljpi9CF4dTyMdzKpKrl4Sgu+w==0vwVKQT8cL0VEEa32bQuLw==

现在我要解密:

decrypt($encrypted, $keys['privatekey']);

returns 这个错误:

PHP Notice: Decryption error in /home/vagrant/code/vendor/phpseclib/phpseclib/phpseclib/Crypt/RSA.php on line 2580

您没有在 decrypt 中正确分解消息:

$sym_key = substr($message, 0, $len);

这包括长度。你可能打算写

$sym_key = substr($message, 3, $len);