Search code examples
phpencryptionrsa

Fatal error: Uncaught Exception: Incorrect public key: error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error


Fatal error: Uncaught Exception: Incorrect public key: error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error in /home/apptestl/domains/apptestlab.pl/public_html/nextalk/zalogowano/crypto_library.php:13 

Stack trace: 
#0 home/apptestl/domains/apptestlab.pl/public_html/nextalk/zalogowano/send_message.php(33): encryptMessage('1', '-----BEGIN PUBL...') 
#1 {main} thrown in /home/apptestl/domains/apptestlab.pl/public_html/nextalk/zalogowano/crypto_library.php on line 13

in code (crypto_library.php -\> encryptMessage function):
@param string $message
 * @param string $publicKey
 * @return string
 */
function encryptMessage($message, $publicKey) {
    $public = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwcfUpZmZxTh5M4mS8OUC Ov+aEHmJu9WMeOp2k/NcEkspQ8WZRitHaSGoIp1dmFlQBqJKUQjm4Amu8hzmNLib IgL0Ihn+//fvA24z1BprEY6MkhYPx0UqP3m19yHpCxHb2fYGCK2QyIwUSnhpO0pW Hg4Y6ciCx5WHdfnD2jvT1Oz2mYHsUbLA9bc3F7QVbBnjYCmqqosz0WWZhDXoF4fi +6gnGe/DL0yxdZkyw8sBmipqAVv9b0hMspY7kkKW4XKQgqtwNXKmQUzEl0O3xh10 Az+AdEr1GrMkGqCJOd+TGp1u/KUZPE0tCKfUCFwKnAHSCoxPE5ERzwfXwTm3NqJ1 dQIDAQAB-----END PUBLIC KEY-----";
    $publicKeyResource = openssl_pkey_get_public($public);
    if (!$publicKeyResource) {
        throw new Exception('Incorrect public key: ' . openssl_error_string());
    }

    // openssl_public_encrypt($message, $encrypted, $publicKeyResource, OPENSSL_PKCS1_OAEP_PADDING);
    openssl_public_encrypt($message, $encrypted, $publicKeyResource, OPENSSL_PKCS1_PADDING);
    openssl_free_key($publicKeyResource);

    return base64_encode($encrypted);
}

code (send_message.php):

<?php
    session_start();
    require_once("../db.php");
    require_once("crypto_library.php");
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'], $_POST['message_to'], $_POST['chat_no'])) {
        $currentLogin = $_SESSION['user_id'];
        $message = trim($_POST['message']);
        $messageTo = $_POST['message_to'];
        $chatNo = $_POST['chat_no'];
        $date = date("Y-m-d H:i:s");
        $userIP = $_SERVER['REMOTE_ADDR'];

        $conn = new mysqli($servername, $username, $password_db, $dbname);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        if (empty($messageTo) || empty($chatNo)) {
            echo "All fields are required.";
            exit();
        } elseif (empty($message)) {
            echo "Empty message.";
            exit();
        }
        $receiverPublicKey = getPublicKey($messageTo);


        $encryptedMessage = encryptMessage($message, $receiverPublicKey);

        $stmt = $conn->prepare("INSERT INTO messages (mess_from, mess_to, message, date, ip, chat_no) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $currentLogin, $messageTo, $encryptedMessage, $date, $userIP, $chatNo);
        if ($stmt->execute()) {
            echo 'success';
        } else {
            echo $stmt->error;
            // echo 'error';
        }

        $stmt->close();
        $conn->close();
    }
?>

please help me to fix this bug


Solution

  • The key is not formatted well as it lacks line endings. Those are required for the PEM format, as you can read in the RFC. So you need to end the line after the header (that ends with the 5 dashes after the BEGIN PUBLIC KEY and after the 64th character on a line of base 64.

    On the other hand, the spaces that are in the base64 definitely should not be there. Otherwise the public key seems to be formatted correctly.