PHP:使用 MCRYPT 加密和解密

PHP: Encrypt and Decrypt with MCRYPT

我已经尝试 encryptdecryptmcrypt

加密工作正常,正如您将在下面的代码中看到的那样,我已经获得了加密数据。

然而,当我尝试解密时出现以下错误:

<br />
<b>Fatal error</b>:  Cannot use object of type stdClass as array in <b>C:\xampp\htdocs\MIAManagerNEWChris - Copy\php\getLogin.php</b> on line <b>63</b><br />

有人知道这是为什么吗?

PHP

error_reporting(E_ALL); 
ini_set('display_errors', 1);

// Start the session
session_start();

// Store command in new variable 
$command = $_POST["command"];

// Create a return object to be sent back to client side
$returnObject = new stdClass();

// Hash key for encrypting selected data
$hashKey = "47sKdUBPqRox7wZtNT48L5hJzQKubqrQ";


function encryptString($string, $mc_key) 
{
    $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $mc_key, trim($string), MCRYPT_MODE_ECB);
    $encode = base64_encode($passcrypt);

    return $encode;
}

function decryptString($string, $mc_key) 
{
    $decoded = base64_decode($string);
    $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $mc_key, $decoded, MCRYPT_MODE_ECB));

    return $decrypted;
}

// Check to see if the command matches and see if an object exists in post
if ($command == "checkUserCredentials")
{
    // Store object from post in new variable
    $receivedObject = json_decode($_POST['userCreds'],true);
    // Check to see if there is a configuration file that exists with users name
    if (!file_exists('C:/xampp/htdocs/ISOSEC/data/users/'. $receivedObject["username"] .'.cfg'))
    {
        // Return back there is no configuration file
        $returnObject->returnMessage = "The configuration for user '" . $receivedObject["username"] . "' not found";
        $returnObject->userExist = "noConfigFile";
    }
    else
    {
        // Return back there is a configuration file
        $returnObject->returnMessage = "The configuration for user '" . $receivedObject["username"] . "' exists";
        $returnObject->userConfigurationFile = "isConfigFile";

        // Check if there is a user name and password been typed
        if (isset($receivedObject["username"]) && isset($receivedObject["password"]))
        {
            // Get information from file
            $userLoginCred = file_get_contents('C:/xampp/htdocs/ISOSEC/data/users/'. $receivedObject["username"] .'.cfg');

            $decrypted = decryptString($userLoginCred, $hashKey);
            $userLoginCredDecoded = json_decode($decrypted);

            // Check if there is a user name and password in configuration file
            if (isset($userLoginCredDecoded["userUsername"]) && isset($userLoginCredDecoded["userPassword"]))
            {
                // Check if user name and password is the same as the configuration user name and password 
                if ($receivedObject["username"] == $userLoginCredDecoded["userUsername"] && $receivedObject["password"] == $userLoginCredDecoded["userPassword"])
                {
                    // Return back an information message
                    $returnObject->validUser = "isValid";

                    // Set session variables
                    $_SESSION["userLoggedIn"] = $userLoginCredDecoded["userUsername"];
                }
                else
                {
                    // Return back error message
                    $returnObject->notValidUser = "notValid";
                }
            }
        }
    }
}

if ($command == "createNewAccount")
{
    // Store object from post in new variable
    $receivedObject = json_decode($_POST['setLoginCreds'], true);

    // Check to see if there is a configuration file that exists with users name
    if (!file_exists('C:/xampp/htdocs/ISOSEC/data/users/'. $receivedObject["userUsername"] .'.cfg'))
    {

        if (strlen($receivedObject["userUsername"]) <= 6 || strlen($receivedObject["userUsername"]) == 0)
        {
            // Return back message about user name length
            $returnObject->inputUsernameLengthValidation = "usernameLength";    
        }

        if (strlen($receivedObject["userPassword"]) <= 6 || strlen($receivedObject["userPassword"]) == 0)
        {
            // Return back message about password length
            $returnObject->inputPasswordLengthValidation = "passwordLength";
        }

        if (strlen($receivedObject["userUsername"]) > 6 && strlen($receivedObject["userPassword"]) > 6)
        {

            // Return back there is no configuration file
            $newConfigurationFile = fopen('C:/xampp/htdocs/ISOSEC/data/users/'. $receivedObject["userUsername"] .'.cfg', "w") or die("Can't create file");
            //$returnObject->returnMessage = $newConfigurationFile; 

            // Check if the new configuration file created
            if ($newConfigurationFile)
            {

                $encrypted = encryptString(json_encode($receivedObject), $hashKey);

                if (fwrite($newConfigurationFile, $encrypted))
                {
                    // Return back message about user configuration created
                    $returnObject->configurationCreated = "configCreated";  
                }
                else
                {
                    // Return back message about user configuration not created
                    $returnObject->configurationCreated = "configNotCreated";   
                }

                fclose($newConfigurationFile);
            }   

            // Return back message saying user account has been created
            $returnObject->returnMessage = "newUserAccountCreated";
        }       
    }
    else
    {
        $returnObject->returnMessage = "configurationAlreadyExist"; 
    }
}

echo json_encode($returnObject);

Javascript

function CheckManagerLoginCredentials(user)
{

    $.post("php/getLogin.php",
    {
        command: "checkUserCredentials",
        userCreds: JSON.stringify(user)
    })

    .success(function (callback)
    {

        console.log(callback);
        var jsonMessage = JSON.parse(callback);

        if (jsonMessage["validUser"] == "isValid")
        {
            // Redirect page to server page
            window.location.href = "index.html";
        }
        else
        {
            // Show error message if the credentials are incorrect
            swal('', "Incorrect credentials entered, please try again", 'error');
        }
    })

    .fail(function (error)
    {
        // Show error dialog if post request failed
        swal('', error, 'error');
    });
}

function CreateNewUserAccount()
{
    swal(
        {
            title: '',
            html: '<br><br><p><label for="setUsernameField">Enter Username: </label> <input id="setUsernameField" placeholder="Username"></p><br><p><label for="setPasswordField">Enter Password: </label> <input id="setPasswordField" type="password" placeholder="Password"></p><p class="createAccountErrorMessage"></p>',
            showCancelButton: true,
            closeOnConfirm: false
        },
        function ()
        {

            var userCredentials = {};
            userCredentials.userUsername = $("#setUsernameField").val();
            userCredentials.userPassword = $("#setPasswordField").val();

            $.post("php/getLogin.php",
            {
                command: "createNewAccount",
                setLoginCreds: JSON.stringify(userCredentials)
            })

            .success(function (callback)
            {

                var jsonMessage = JSON.parse(callback);

                $(".createAccountErrorMessage").html("");

                if (jsonMessage["inputUsernameLengthValidation"])
                {
                    // Show error message if username not longer enough
                    $(".createAccountErrorMessage").css("display","block").append("<li>Username MUST be longer than 6 characters</li>");
                }

                if (jsonMessage["inputPasswordLengthValidation"])
                {
                    // Show error message if password not longer enough
                    $(".createAccountErrorMessage").css("display","block").append("<li>Password MUST be longer than 6 characters</li>");
                }

                if (jsonMessage["returnMessage"] == "configurationAlreadyExist")
                {
                    // Show error message if username already exist
                    $(".createAccountErrorMessage").css("display","block").append("<li>This username already exists, please try again!</li>");
                }

                if (jsonMessage["returnMessage"] == "newUserAccountCreated")
                {
                    // Show success message
                    $(".createAccountErrorMessage").css("display","block").css("color","green").append("Account has successfully been created.");
                    // Remove create account panel
                    setTimeout(function()
                    {
                        $(".sweet-overlay").css("display", "none");
                        $(".sweet-alert").css("display", "none");
                    }, 2000);
                }
            })

            .fail(function (error)
            {
                // Show error dialogue if post request failed
                swal('', error, 'error');
            });
        });
}

Cannot use object of type stdClass as array in C:\xampp\htdocs\MIAManagerNEWChris - Copy\php\getLogin.php on line 63

这里的错误指出出了什么问题。您的所有 encrypt/decrypt 代码都运行正常,但您只是误用了 json_decode() 的输出。在 json_decode() 之后的后续代码中,您正在访问数组元素,但原始代码实际上是 returning 一个对象 stdClass,看起来像:

class stdClass#1 (2) {
  public $userUsername =>
  string(9) "testing55"
  public $userPassword =>
  string(7) "1234567"
}

所以你只需要切换到像 $userLoginCredDecoded->userUsername 这样的对象属性而不是 [] 数组语法,或者更容易地将 TRUE 作为第二个参数传递给 json_decode()强制它 return 一个关联数组。

json_decode($decrypted, TRUE);