note 105949 modified in function.crypt by danbrown

From: Date: Tue, 27 Sep 2011 14:19:24 +0000
Subject: note 105949 modified in function.crypt by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-183481@lists.php.net to get a copy of this message
I made a nice little wrapper function for crypt(): <?php function hasher($info, $encdata = false) { $strength = "08"; //if encrypted data is passed, check it against input ($info) if ($encdata) { if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) { return true; } else { return false; } } else { //make a salt and hash it with input, and add salt to end $salt = ""; for ($i = 0; $i < 22; $i++) { $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1); } //return 82 char string (60 char hash & 22 char salt) return crypt($info, "$2a$".$strength."$".$salt).$salt; } } ?> This wrapper will accept a string as input and hash it, and output the hash result of the string and salt together, plus the salt added on the end. You can then store that output in a db, and pass it on to the function as the 2nd parameter when you go to verify it, along with the user input or whatever as the first. Examples: <?php $hash = hasher($userinput); if ($hash == hasher($userinput, $hash) {//authed} ?> Neat huh? --was-- I made a nice little wrapper function for crypt(): function hasher($info, $encdata = false) { $strength = "08"; //if encrypted data is passed, check it against input ($info) if ($encdata) { if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) { return true; } else { return false; } } else { //make a salt and hash it with input, and add salt to end $salt = ""; for ($i = 0; $i < 22; $i++) { $salt .= substr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", rand(0, 61), 1); } //return 82 char string (60bit hash & salt) return crypt($info, "$2a$".$strength."$".$salt).$salt; } } This wrapper will accept a string as input and hash it, and output the hash result of the string and salt together, plus the salt added on the end. You can then store that output in a db, and pass it on to the function as the 2nd parameter when you go to verify it, along with the user input or whatever as the first. Examples: $hash = hasher($userinput); if ($hash == hasher($userinput, $hash) {//authed} Neat huh? http://php.net/manual/en/function.crypt.php

« previous php.notes (#183481) next »