我想使用非对称密钥加密和解密字符串。由于字符串可以更大,我决定尝试这样的混合解决方案:<?phpuse 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);
1 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
您没有正确分解消息decrypt
:
$sym_key = substr($message, 0, $len);
这包括长度。你可能想写
$sym_key = substr($message, 3, $len);
- 1 回答
- 0 关注
- 424 浏览
添加回答
举报
0/150
提交
取消