2012-09-04 49 views
0

我在我的android應用程序中實現了密碼更改功能,並且我在我的php文件中編碼了密碼哈希。用戶可以更改密碼並將密碼存儲在數據庫中。當我嘗試使用電子郵件和新密碼登錄時,它會告訴我不正確的密碼。我在哪裏做錯了我的PHP文件?在PHP中更改密碼問題

這是我的PHP文件中的代碼:

<?php 

// array for JSON response 
$response = array(); 

function hashSSHA($newpassword) { 
    $salt = mhash('sha512', rand()); 
    $salt = substr($salt, 0, 15); 
    $encrypted = hash('sha512', $newpassword . $salt, true) . $salt; 
    $hash = array("salt" => $salt, "encrypted" => $encrypted); 
    return $hash; 
} 

// check for required fields 
if (isset($_POST['email']) && isset($_POST['newpassword'])) { 
    $email = $_POST['email']; 
    $newpassword = $_POST['newpassword']; 

    // include db connect class 
    require_once __DIR__ . '/db_connect.php'; 

    // connecting to db 
    $db = new DB_CONNECT(); 

    // TESTING HERE FOR STORING NEW PASSWORD INTO DATABASE 
    $hash = hashSSHA($newpassword); 
    $encrypted_password = $hash["encrypted"]; // encrypted password 
    $salt = $hash["salt"]; // salt 

    $result = mysql_query("UPDATE users SET encrypted_password = '$encrypted_password', salt = '$salt' WHERE email = '$email'"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully updated 
     $response["success"] = 1; 
     $response["message"] = "Password successfully changed"; 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 
     $response["success"] = 0; 
     $response["message"] = "Password change failed"; 
     echo json_encode($response); 
    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

    // echoing JSON response 
    echo json_encode($response); 
} 
?> 

編輯 這是我的解密功能

// DECRYPTING user currentpassword 
function checkhashSSHA($salt, $currentpassword) { 

$hash = hash('sha512', $currentpassword . $salt, true) . $salt; 
return $hash; 
} 
+0

檢查'mhash'庫是否安裝 – diEcho

+0

描述用戶密碼在他們嘗試登錄時如何驗證。 – jtheman

+2

此代碼非常容易受到SQL注入攻擊! – JvdBerg

回答

1

有相當多的代碼中的問題。

首先,SHA512不是散列密碼的好選擇,因爲它太快了。 Bcrypt專門用於哈希密碼,因此速度慢(需要計算時間)。建議使用像phpass這樣一個完善的庫,如果你想了解如何實現它,你可以閱讀這article,我試圖解釋最重要的一點。

1)您的代碼中的第一個問題可能是,mhash()爲您的鹽產生二進制輸出。我不知道爲什麼你將它附加到你的密碼哈希(這不是鹽的應用方式),但變量$encrypted後會包含二進制數據。

2)這會導致第二個問題,即將變量插入到更新語句中。將二進制數據插入sql將導致無效聲明。在添加到sql語句之前,您應該始終轉義數據,在您的情況下使用mysql_escape_string()

3)接下來的問題是,不推薦使用mysql_ *函數,而是使用mysqli或PDO進行數據庫訪問。

4)我們在問題2中遇到的另一個問題是,如果沒有轉義數據,就容易受到SQL注入攻擊。想象一下,有人可以用這個用戶輸入操作

WHERE電子郵件=「abc' OR email <> '

...他可以爲所有用戶立刻重置密碼!

這就是說,我真的建議,你重新考慮使用Bcrypt。