1

I've attempted to encrypt and decrypt with mcrypt.

The encryption is working fine, as you'll see below in my code I've got the encrypted data.

However when I try to decrypt I'm getting the following error:

<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 />

Does anybody know why this is?

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');
            });
        });
}
12
  • " it's not doing anything" - Clarification? Commented Aug 17, 2015 at 12:20
  • @Layke nothing being returned, no feed back why it's not working. I don't even know why the decrypt isn't working as I have to decrypt before doing the json_decode the data Commented Aug 17, 2015 at 12:33
  • If truly nothing is happening when you expect output, ensure you have error reporting enabled and displaying on screen. error_reporting(E_ALL); ini_set('display_errors', 1); Commented Aug 17, 2015 at 13:10
  • 1
    After $decrypted = decryptString($userLoginCred, $hashKey); do a var_dump($decrypted); because when I tested your originally posted, abbreviated code, I got back a stdClass object, not an associative array. But you are accessing array keys in your code. You may need to switch to object syntax or use json_decode($decrypted, TRUE) passing true as the second param to force it to return an array. Commented Aug 17, 2015 at 13:17
  • 2
    This encryption code is horrendously insecure. ECB mode, padding oracle vulnerabilities (rtrim()), and no MAC. Commented Aug 17, 2015 at 13:48

1 Answer 1

2

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

The error here identifies what went wrong. All of your encrypt/decrypt code is functioning correctly, but you're just misusing the output from json_decode(). In the subsequent code after json_decode(), you're accessing array elements but the original code is actually returning an object stdClass that looks like:

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

So you merely need to either switch to object properties like $userLoginCredDecoded->userUsername instead of [] array syntax, or more easily pass TRUE as the second argument to json_decode() to force it to return an associative array.

json_decode($decrypted, TRUE);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this Michael :)
Cheers, have a great day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.