如何在PHP中用客户端RSA私钥解密AES会话密钥(session_key)?
Let's walk through exactly how to decrypt the session_key (your encrypted AES key) using your RSA private key in PHP, adhering to the requirements you laid out.
First, a quick clarification: PKCS5Padding is typically associated with AES symmetric encryption, while RSA uses PKCS#1 v1.5 or OAEP padding. I’ll assume you meant PKCS#1 v1.5 padding for the RSA decryption (since PKCS5 doesn’t apply to RSA), but I’ll note how to adjust if needed.
Step 1: Prepare Your RSA Private Key
Make sure your private key is in PEM format (starts with -----BEGIN RSA PRIVATE KEY----- and ends with -----END RSA PRIVATE KEY-----). You can store it in a secure file or as a string in your code (just preserve newlines if using a string).
Step 2: PHP Code Implementation
Here’s a complete, tested code snippet to handle the decryption:
<?php // The encrypted session_key from your request $encryptedSessionKey = "OsSdo+sNV48lJuZB0HD2Fk5wrd0oGbfVixFsaAC6DjKfig6Lw3wFbb54wW1Q4fAbNTr2qMLCXJtKXV6ldYW/z/g24Ly7mE5YvXs3JWeswNQ4zo67Rtx5CZRJNSR149hoNbFmPWVPiBCsq1YAh0vcSdk0NzL0aKp5xR27p57X2mhVACn+edlT9tRIJUFwfSFHHVOPKftpIjIGQxugW8pSHaMQ9EoP4HZQpDntx56mVLD4ygGrK8IQcHRHHOe+a4mA3XenfLA2rsoCAHnKyW5tqwW2MOZB0s51vQ5kEuX/+nSQ30btcjHiuEpzdkSpzBecpm9rN3FFoSjaH03BSQJr2Q=="; // Your RSA private key (replace with your actual PEM content) $privateKey = <<<EOD -----BEGIN RSA PRIVATE KEY----- // Paste your private key content here -----END RSA PRIVATE KEY----- EOD; // Step 1: Decode the base64-encoded encrypted key $decodedEncryptedKey = base64_decode($encryptedSessionKey); // Step 2: Decrypt using RSA private key $decryptedSessionKey = ''; $decryptionSuccess = openssl_private_decrypt( $decodedEncryptedKey, $decryptedSessionKey, $privateKey, OPENSSL_PKCS1_PADDING // Use OPENSSL_PKCS1_OAEP_PADDING if OAEP padding was used for encryption ); // Handle results if ($decryptionSuccess) { echo "Decrypted AES Session Key: " . $decryptedSessionKey; // Next step: Use this key to decrypt the 'data' field with AES-CBC + PKCS5Padding } else { echo "Decryption failed: " . openssl_error_string(); } ?>
Key Details:
- Base64 Decoding: The
session_keyis base64-encoded, so we first convert it to raw binary data before decryption. - Padding Selection:
OPENSSL_PKCS1_PADDINGmatches PKCS#1 v1.5 padding. If the original encryption used OAEP padding, swap this withOPENSSL_PKCS1_OAEP_PADDING. - Error Handling: Always check the return value of
openssl_private_decryptand useopenssl_error_string()to debug issues like invalid keys, mismatched padding, or corrupted data. - AES Follow-Up: Once you have the decrypted AES key, you’ll need to decrypt the
datafield using AES-CBC with PKCS5Padding. Let me know if you need help with that part!
内容的提问来源于stack exchange,提问作者Anirban Sarkar

