Object of class .. could not be converted to string
I made my first class and I'm having trouble converting the objects back into strings.
class Cryption
{
var $data;
var $salt;
function __construct($data, $salt)
{
$this->data = $data;
$this->salt = $salt;
}
function sha512()
{
$sodium = 'Na';
return hash_hmac("sha512", $this->data . $this->salt, $sodium);
}
function encrypt()
{
$salt = substr(sha512(($this->key), 'brownies'), 0, 30);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $this->data, MCRYPT_MODE_CBC, md5($salt)));
}
When I use it:
$password = new Cryption(mysql_real_escape_string(trim($_POST['password'])), 'pepper');
$password->sha512();
It says 'PHP Catchable fatal error: Object of class Cryption could not be converted 开发者_StackOverflow社区to string'
I don't really know how to get it back into a string. May someone please help me?
Thank you.
Edit:
<?php
require("config.php");
include("includes/cryption/cryption.php");
$username = mysql_real_escape_string(trim($_POST['username']));
$password = new Cryption(mysql_real_escape_string(trim($_POST['password'])), 'pepper'); //use a different salt next time such as a special salt for each user
$password->sha512();
$result = mysql_query("SELECT * FROM `administrators` WHERE username='$username' and password='$password'");
$row = mysql_fetch_row($result);
$count = mysql_num_rows($result);
if ($count == 1) {
if (isset($_POST['remember'])) {
session_start();
$_SESSION['user'] = array(
'id' => $row[0],
'username' => $row[1],
'password' => $row[2]
);
$userid = new Cryption($_SESSION['user']['id'], 'kkfishing');
$session = new Cryption($_SESSION['user']['username'], 'kkfishing');
$validated = new Cryption($_SESSION['user']['password'], 'kkfishing');
setcookie("uniqueid", $userid->encrypt(), time() + 60 * 60 * 24 * 100, "/"); //100 days
setcookie("kksessionid", $session->encrypt(), time() + 60 * 60 * 24 * 100, "/");
setcookie("kkuserid", $validated->encrypt(), time() + 60 * 60 * 24 * 100, "/");//disguised cookie name
}
session_start();
$_SESSION['authenticated'] = $row[0];
echo '1'; //true
exit;
}
else
{
echo '0'; //false
exit;
}
?>
Look at this lines:
$password->sha512();
$result = mysql_query("SELECT * FROM `administrators` WHERE username='$username' and password='$password'");
$password
is an object. It should be:
$pw = $password->sha512();
$result = mysql_query("SELECT * FROM `administrators` WHERE username='$username' and password='$pw'");
The same error can be encountered when initializing the constructor variable in a wrong way like below:
function __construct($data, $salt)
{
$this->$data = $data; //mistakenly using $ (dollar) sign after `$this->`
$this->$salt = $salt;
}
Where the correct way of initializing is:
function __construct($data, $salt)
{
$this->data = $data;
$this->salt = $salt;
}
精彩评论