Example #1
0
 public function setPassword($password)
 {
     if ($this->validatesAgainstStupidPass($password)) {
         $this->salt = substr(md5(uniqid('', true)), 0, 8);
         $this->password = base64_encode(pbkdf2($password, $this->salt));
     }
 }
 public function signup()
 {
     if ($this->request->is('post')) {
         $table = TableRegistry::get('Users');
         $salt = uniqid(mt_rand(), true);
         $user = $table->newEntity(['name' => $this->request->data('name'), 'email' => $this->request->data('email'), 'password' => pbkdf2("sha256", $this->request->data('password'), $salt), 'salt' => $salt, 'date_created' => Time::createFromTimestamp(time())]);
         if ($user->isValid() && $this->request->data('password') == $this->request->data('confirm_password') && $table->save($user)) {
             $key = $user->makeKey();
             $this->Cookie->write('ta_login_id', $user->id);
             $this->Cookie->write('ta_login_email', $user->email);
             $this->Cookie->write('ta_login_key', $key);
             return $this->redirect("/");
         } else {
             if ($user->isValid()) {
                 if ($this->request->data('password') == $this->request->data('confirm_password')) {
                     $this->Flash->set('The email you entered is already in use.', ['element' => 'error']);
                 } else {
                     $this->Flash->set('The password and confirmation you entered did not match.', ['element' => 'error']);
                 }
             } else {
                 $this->Flash->set('Please make sure your email is valid and name is longer than three characters.', ['element' => 'error']);
             }
         }
     }
     $this->viewBuilder()->layout("auth");
 }
 protected function authenticate()
 {
     $key = pbkdf2("sha1", $this->encryptPassword(), $this->challengeData, 16, 20, true);
     $this->_inputKey = new KeyStream($key);
     $this->_outputKey = new KeyStream($key);
     $array = $this->_phoneNumber . $this->challengeData . time();
     $response = $this->_outputKey->encode($array, 0, strlen($array), false);
     return $response;
 }
Example #4
0
function validate_password($password, $good_hash)
{
    $params = explode(":", $good_hash);
    if (count($params) < HASH_SECTIONS) {
        return false;
    }
    $pbkdf2 = base64_decode($params[HASH_PBKDF2_INDEX]);
    return slow_equals($pbkdf2, pbkdf2($params[HASH_ALGORITHM_INDEX], $password, $params[HASH_SALT_INDEX], (int) $params[HASH_ITERATION_INDEX], strlen($pbkdf2), true));
}
function cpg_password_validate($password, $correct_hash)
{
    if (is_array($correct_hash)) {
        $params = array(HASH_ALGORITHM_INDEX => $correct_hash['user_password_hash_algorithm'], HASH_ITERATION_INDEX => $correct_hash['user_password_iterations'], HASH_SALT_INDEX => $correct_hash['user_password_salt'], HASH_PBKDF2_INDEX => $correct_hash['user_password']);
    } else {
        $params = explode(":", $correct_hash);
    }
    if (count($params) < HASH_SECTIONS) {
        return false;
    }
    $pbkdf2 = base64_decode($params[HASH_PBKDF2_INDEX]);
    return slow_equals($pbkdf2, pbkdf2($params[HASH_ALGORITHM_INDEX], $password, $params[HASH_SALT_INDEX], (int) $params[HASH_ITERATION_INDEX], strlen($pbkdf2), true));
}
Example #6
0
 public function testTestVectors2()
 {
     $password = '******';
     $salt = 'ATHENA.MIT.EDUraeburn';
     $len = 16;
     $algo = 'sha1';
     $iter = 1;
     $len = 16;
     $this->assertEquals('cdedb5281bb2f801565a1122b2563515', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 1;
     $len = 32;
     $this->assertEquals('cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 2;
     $len = 16;
     $this->assertEquals('01dbee7f4a9e243e988b62c73cda935d', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 2;
     $len = 32;
     $this->assertEquals('01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 1200;
     $len = 16;
     $this->assertEquals('5c08eb61fdf71e4e4ec3cf6ba1f5512b', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 1200;
     $len = 32;
     $this->assertEquals('5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 5;
     $salt = pack('H*', '1234567878563412');
     $len = 16;
     $this->assertEquals('d1daa78615f287e6a1c8b120d7062a49', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $iter = 5;
     $len = 32;
     $this->assertEquals('d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $password = '******';
     $salt = 'pass phrase equals block size';
     $len = 16;
     $iter = 1200;
     $this->assertEquals('139c30c0966bc32ba55fdbf212530ac9', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $len = 32;
     $this->assertEquals('139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $password = '******';
     $salt = 'pass phrase exceeds block size';
     $len = 16;
     $iter = 1200;
     $this->assertEquals('9ccad6d468770cd51b10e6a68721be61', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
     $len = 32;
     $this->assertEquals('9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a', bin2hex(pbkdf2($password, $salt, $iter, $len, $algo)));
 }
Example #7
0
function generateRequestToken($country, $phone)
{
    $waString = "UxYPUgMKRMKDEMKCwprCjcKMRjohaSlXQQ==";
    $noMediaHash = "AAGpM5zvDnFyrsmemfAETcw/kPWMRcCoW96rBU2pphtEOCWNVhSp8QX6";
    $waPrefix = "Y29tLndoYXRzYXBw";
    $signature = "MIIDMjCCAvCgAwIBAgIETCU2pDALBgcqhkjOOAQDBQAwfDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMRYwFAYDVQQKEw1XaGF0c0FwcCBJbmMuMRQwEgYDVQQLEwtFbmdpbmVlcmluZzEUMBIGA1UEAxMLQnJpYW4gQWN0b24wHhcNMTAwNjI1MjMwNzE2WhcNNDQwMjE1MjMwNzE2WjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExFjAUBgNVBAoTDVdoYXRzQXBwIEluYy4xFDASBgNVBAsTC0VuZ2luZWVyaW5nMRQwEgYDVQQDEwtCcmlhbiBBY3RvbjCCAbgwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqA4GFAAKBgQDRGYtLgWh7zyRtQainJfCpiaUbzjJuhMgo4fVWZIvXHaSHBU1t5w//S0lDK2hiqkj8KpMWGywVov9eZxZy37V26dEqr/c2m5qZ0E+ynSu7sqUD7kGx/zeIcGT0H+KAVgkGNQCo5Uc0koLRWYHNtYoIvt5R3X6YZylbPftF/8ayWTALBgcqhkjOOAQDBQADLwAwLAIUAKYCp0d6z4QQdyN74JDfQ2WCyi8CFDUM4CaNB+ceVXdKtOrNTQcc0e+t";
    $classesMd5 = "30CnAF22oY+2PUD5pcJGqw==";
    $k = "PkTwKSZqUfAUyR0rPQ8hYJ0wNsQQ3dW1+3SCnyTXIfEAxxS75FwkDf47wNv/c8pP3p0GXKR6OOQmhyERwx74fw1RYSU10I4r1gyBVDbRJ40pidjM41G1I1oN";
    $KEY = "The piano has been drinking";
    //TODO: This phone prefix split XXX-ZZZZZ... is ok for +34 numbers, but needs to be checked
    //      for other countries
    $phone1 = substr($phone, 0, 3);
    $phone2 = substr($phone, 3);
    // This AES secret is not really needed right now
    $id = base64_decode($waString) . $country . $phone2;
    $salt = substr(base64_decode($noMediaHash), 2, 4);
    $key = pbkdf2('sha1', $id, $salt, 16, 16, true);
    $iv = substr(base64_decode($noMediaHash), 6, 16);
    $data = substr(base64_decode($noMediaHash), 22);
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'nofb', '');
    mcrypt_generic_init($td, $key, $iv);
    $aes_secret = mcrypt_generic($td, $data);
    mcrypt_module_close($td);
    // We xor this file because I don't want to have a copyrighted png
    // on my repository
    $f = file_get_contents("magic.dat");
    $count = 0;
    for ($i = 0; $i < strlen($f); $i++) {
        $f[$i] = $f[$i] ^ $KEY[$count++];
        if ($count == strlen($KEY) - 1) {
            $count = 0;
        }
    }
    $d = base64_decode($waPrefix) . $f;
    $key2 = pbkdf2('sha1', $d, base64_decode($k), 128, 80, true);
    $data = base64_decode($signature) . base64_decode($classesMd5) . $phone;
    $opad = str_repeat(chr(0x5c), 64);
    $ipad = str_repeat(chr(0x36), 64);
    for ($i = 0; $i < 64; $i++) {
        $opad[$i] = $opad[$i] ^ $key2[$i];
        $ipad[$i] = $ipad[$i] ^ $key2[$i];
    }
    $output = hash("sha1", $opad . hash("sha1", $ipad . $data, true), true);
    return base64_encode($output);
}
 protected function realLogin($user, $pass)
 {
     $query = 'SELECT ' . MYSQLI_NICHT_AUTH_COL_PASS . ', ' . MYSQLI_NICHT_AUTH_COL_SALT . '
           FROM ' . MYSQLI_NICHT_AUTH_TABLE . '
           WHERE ' . MYSQLI_NICHT_AUTH_COL_USER . '=?;';
     if ($stmt = $this->db->prepare($query)) {
         $stmt->bind_param('s', $user);
         // user is case insensitive
         $stmt->bind_result($dbhash, $dbsalt);
         $stmt->execute();
         $stmt->fetch();
         if (empty($dbhash)) {
             throw new Exception('Cant find this username', -1);
         }
         if (base64_encode(pbkdf2($pass, $dbsalt)) != $dbhash) {
             throw new Exception('Bad Password', -2);
         }
         return;
     }
     throw new Exception('Something went terribly wrong' - 10);
 }
Example #9
0
/**
 * decrypt()
 *
 * decrypt a crypted string
 */
function decrypt($encrypted, $personalSalt = "")
{
    if (!isset($_SESSION['settings']['cpassman_dir']) || empty($_SESSION['settings']['cpassman_dir'])) {
        require_once '../includes/libraries/Encryption/PBKDF2/PasswordHash.php';
    } else {
        require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Encryption/PBKDF2/PasswordHash.php';
    }
    if (!empty($personalSalt)) {
        $staticSalt = $personalSalt;
    } else {
        $staticSalt = SALT;
    }
    //base64 decode the entire payload
    $encrypted = base64_decode($encrypted);
    // get the salt
    $pbkdf2Salt = substr($encrypted, -64);
    //remove the salt from the string
    $encrypted = substr($encrypted, 0, -64);
    //$key = strHashPbkdf2($staticSalt, $pbkdf2Salt, ITCOUNT, 16, 'sha256', 32);
    $key = substr(pbkdf2('sha256', $staticSalt, $pbkdf2Salt, ITCOUNT, 16 + 32, true), 32, 16);
    // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
    $iv = base64_decode(substr($encrypted, 0, 43) . '==');
    // Remove $iv from $encrypted.
    $encrypted = substr($encrypted, 43);
    // Retrieve $mac which is the last 64 characters of $encrypted.
    $mac = substr($encrypted, -64);
    // Remove the last 64 chars from encrypted (remove MAC)
    $encrypted = substr($encrypted, 0, -64);
    //verify the sha256hmac from the encrypted data before even trying to decrypt it
    if (hash_hmac('sha256', $encrypted, $staticSalt) != $mac) {
        return false;
    }
    // Decrypt the data.
    $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), "");
    // Yay!
    return $decrypted;
}
Example #10
0
 }
 $t1 = microtime(true);
 print "pbkdf2\tsha-1\t{$count}\t" . $imax / ($t1 - $t0) . " RPS\n";
 $algo = 'sha256';
 $len = 32;
 $t0 = microtime(true);
 for ($i = 0; $i < $imax; ++$i) {
     $tmp = pbkdf2($password, $salt, $count, $len, $algo);
 }
 $t1 = microtime(true);
 print "pbkdf2\tsha-256\t{$count}\t" . $imax / ($t1 - $t0) . " RPS\n";
 $algo = 'sha512';
 $len = 32;
 $t0 = microtime(true);
 for ($i = 0; $i < $imax; ++$i) {
     $tmp = pbkdf2($password, $salt, $count, $len, $algo);
 }
 $t1 = microtime(true);
 print "pbkdf2\tsha-512\t{$count}\t" . $imax / ($t1 - $t0) . " RPS\n";
 $count = 5000;
 $t0 = microtime(true);
 for ($i = 0; $i < $imax; ++$i) {
     $tmp = Crypt2007::crypt_sha512($password, $count, $salt, true);
 }
 $t1 = microtime(true);
 print "crypt_sha512 native\t{$count}\t" . $imax / ($t1 - $t0) . " RPS\n";
 $t0 = microtime(true);
 for ($i = 0; $i < $imax; ++$i) {
     $tmp = Crypt2007::crypt_sha512($password, $count, $salt, false);
 }
 $t1 = microtime(true);
Example #11
0
 */
require_once 'PasswordHash.php';
echo "Sample hash:\n";
$hash = create_hash("test_password");
echo $hash . "\n";
echo "\nTest results:\n";
// Test vector raw output.
$a = bin2hex(pbkdf2("sha1", "password", "salt", 2, 20, true));
$b = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
if ($a === $b) {
    echo "pass\n";
} else {
    echo "FAIL\n";
}
// Test vector hex output.
$a = pbkdf2("sha1", "password", "salt", 2, 20, false);
$b = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
if ($a === $b) {
    echo "pass\n";
} else {
    echo "FAIL\n";
}
$hash_of_password = create_hash("password");
// Test correct password.
if (validate_password("password", $hash_of_password)) {
    echo "pass\n";
} else {
    echo "FAIL\n";
}
// Test wrong password.
if (validate_password("wrong_password", $hash_of_password) === FALSE) {
Example #12
0
        echo "FAIL: [{$msg}]\n";
    }
}
// The following test vectors were taken from RFC 6070.
// https://www.ietf.org/rfc/rfc6070.txt
$pbkdf2_vectors = array(array('algorithm' => 'sha1', 'password' => "password", 'salt' => "salt", 'iterations' => 1, 'keylength' => 20, 'output' => "0c60c80f961f0e71f3a9b524af6012062fe037a6"), array('algorithm' => 'sha1', 'password' => "password", 'salt' => "salt", 'iterations' => 2, 'keylength' => 20, 'output' => "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), array('algorithm' => 'sha1', 'password' => "password", 'salt' => "salt", 'iterations' => 4096, 'keylength' => 20, 'output' => "4b007901b765489abead49d926f721d065a429c1"), array('algorithm' => 'sha1', 'password' => "passwordPASSWORDpassword", 'salt' => "saltSALTsaltSALTsaltSALTsaltSALTsalt", 'iterations' => 4096, 'keylength' => 25, 'output' => "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), array('algorithm' => 'sha1', 'password' => "password", 'salt' => "salt", 'iterations' => 4096, 'keylength' => 16, 'output' => "56fa6aa75548099dcc37d7f03425e0c3"));
foreach ($pbkdf2_vectors as $test) {
    $realOut = pbkdf2($test['algorithm'], $test['password'], $test['salt'], $test['iterations'], $test['keylength'], false);
    assert_true($realOut === $test['output'], "PBKDF2 vector");
}
$good_hash = create_hash("foobar");
assert_true(validate_password("foobar", $good_hash), "Correct password");
assert_true(validate_password("foobar2", $good_hash) === false, "Wrong password");
$h1 = explode(":", create_hash(""));
$h2 = explode(":", create_hash(""));
assert_true($h1[HASH_PBKDF2_INDEX] != $h2[HASH_PBKDF2_INDEX], "Different hashes");
assert_true($h1[HASH_SALT_INDEX] != $h2[HASH_SALT_INDEX], "Different salts");
assert_true(slow_equals("", ""), "Slow equals empty string");
assert_true(slow_equals("abcdef", "abcdef"), "Slow equals normal string");
assert_true(slow_equals("aaaaaaaaaa", "aaaaaaaaab") === false, "Slow equals different");
assert_true(slow_equals("aa", "a") === false, "Slow equals different length 1");
assert_true(slow_equals("a", "aa") === false, "Slow equals different length 2");
echo "Example hash: {$good_hash}\n";
// benchmark
for ($i = 0; $i < 25; $i++) {
    $count = pow(2, $i);
    $start = microtime(true);
    $hash = pbkdf2("sha256", "password", "salt", $count, 32);
    $time = microtime(true) - $start;
    printf("%10d iterations: %f seconds\n", $count, $time);
}
Example #13
0
function teampass_decrypt_pw($encrypted, $salt, $rand_key, $itcount = 2072)
{
    require_once '../includes/libraries/Encryption/PBKDF2/PasswordHash.php';
    $encrypted = base64_decode($encrypted);
    $pass_salt = substr($encrypted, -64);
    $encrypted = substr($encrypted, 0, -64);
    //$key       = teampass_pbkdf2_hash($salt, $pass_salt, $itcount, 16, 32);
    $key = substr(pbkdf2('sha256', $salt, $pass_salt, $itcount, 16 + 32, true), 32, 16);
    $iv = base64_decode(substr($encrypted, 0, 43) . '==');
    $encrypted = substr($encrypted, 43);
    $mac = substr($encrypted, -64);
    $encrypted = substr($encrypted, 0, -64);
    if ($mac !== hash_hmac('sha256', $encrypted, $salt)) {
        return null;
    }
    //return substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), "\0\4"), strlen($rand_key));
    $result = substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), ""), strlen($rand_key));
    if ($result) {
        return $result;
    } else {
        return "";
    }
}
Example #14
0
function vidtrial_decrypt_string($crypt_string, $key)
{
    /** given a string ``$crypt_string`` containing the following items:
        algo$mode$kdfalgo$kdfmode$kdfrounds$kdfsalt$iv$crypto.
        decrypt the string with the given key
    */
    require_once plugin_dir_path(__FILE__) . "exceptions.php";
    $crypt = explode('$', $crypt_string, 8);
    if (count($crypt) !== 8) {
        throw new Exception("invalid crypt string");
    }
    $algo = $crypt[0];
    $mode = $crypt[1];
    $kdfalgo = $crypt[2];
    $kdfmode = $crypt[3];
    $kdfrounds = $crypt[4];
    $salt = base64_decode($crypt[5]);
    $iv = base64_decode($crypt[6]);
    $ciphertext = base64_decode($crypt[7]);
    $td = mcrypt_module_open($algo, '', $mode, '');
    switch ($kdfalgo) {
        case 'pbkdf2':
            $derived_key = pbkdf2($kdfmode, $key, $salt, (int) $kdfrounds, mcrypt_enc_get_key_size($td), true);
            if ($derived_key === false) {
                throw new ValueError("Failed key derivation");
            }
            break;
            //add your methods here
        //add your methods here
        default:
            throw ValueError("unknown key derivation function {$kdfalgo}");
    }
    mcrypt_generic_init($td, $derived_key, $iv);
    $cleartext = mdecrypt_generic($td, $ciphertext);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $cleartext;
}
                }
                break;
        }
    }
    return $p;
}
if (isset($_POST['user_initiated'])) {
    $gen_pass = $_POST['password'];
    $force_new_password = '******';
} else {
    $gen_pass = generatePassword();
    $force_new_password = '******';
}
$private_key = genKey();
$salt = CC_SALT;
$hash = pbkdf2($gen_pass, $salt, 1000, 32);
$pass = base64_encode($hash);
$first_name = ucwords(strtolower($_POST['first_name']));
$last_name = ucwords(strtolower($_POST['last_name']));
$q = $dbh->prepare("INSERT INTO `cm_users` (`id`, `first_name`, `last_name`, `email`, `mobile_phone`, `home_phone`, `grp`, `username`, `password`, `timezone_offset`, `picture_url`,`status`, `new`, `date_created`, `private_key`,`force_new_password`) VALUES (NULL, :first_name, :last_name, :email, :mobile_phone, :home_phone, :grp, :username, :pass, :timezone, 'people/no_picture.png', 'inactive', 'yes', CURRENT_TIMESTAMP, :private_key,:force_new_password);");
$data = array('first_name' => $first_name, 'last_name' => $last_name, 'email' => $_POST['email'], 'mobile_phone' => $_POST['mobile_phone'], 'home_phone' => $_POST['home_phone'], 'grp' => $_POST['grp'], 'username' => $new_username, 'pass' => $pass, 'timezone' => $_POST['timezone_offset'], 'private_key' => $private_key, 'force_new_password' => $force_new_password);
$q->execute($data);
$error = $q->errorInfo();
if ($error[1]) {
    $response = array('error' => true, 'message' => 'Sorry, there was an error.');
    echo json_encode($response);
} else {
    //Send email to applicant
    $subject = "ClinicCases " . CC_PROGRAM_NAME . ": Thanks for applying";
    $message = "Your application for ClinicCases has been received.  It will be reviewed by your administrator.  When it is approved, your administrator will send you another email letting you know your account is active.\n\nIn the meantime, feel free to contact your administrator at " . CC_ADMIN_EMAIL . " with any questions.";
    mail($_POST['email'], $subject, $message, CC_EMAIL_HEADERS, "-f " . CC_EMAIL_FROM);
Example #16
0
        $output .= $xorsum;
    }
    if ($raw_output) {
        return substr($output, 0, $key_length);
    } else {
        return bin2hex(substr($output, 0, $key_length));
    }
}
$algo = "sha1";
$pass = user_input();
// symbolic input
$salt = user_input();
// symbolic input
$count = 1;
$key_len = 16;
$result = pbkdf2($algo, $pass, $salt, $count, $key_len);
label("after-call");
function strtolower($s)
{
    return $s;
}
function in_array($x, $array)
{
    foreach ($array as $elem) {
        if ($x == $elem) {
            return true;
        }
    }
    return false;
}
function hash_algos()
}
$stmt->bind_param("s", $name);
$stmt->execute();
if ($stmt->errno) {
    print "error: " . $stmt->error;
    exit;
}
// check if user exists (if there is a result the user exists)
$stmt->store_result();
if ($stmt->num_rows > 0) {
    $stmt->bind_result($hash, $salt, $algorithm, $iterations);
    $stmt->fetch();
    $stmt->close();
    $salt = base64_decode($salt);
    // create hash to check against db
    $hashCheck = pbkdf2($algorithm, $pass, $salt, $iterations, $hash_size, false);
    //check hash
    if ($hash == $hashCheck) {
        // set current session to user when hash matches
        if ($stmt = $con->prepare("UPDATE `users` SET `session` = ? WHERE `name` = ?")) {
            $stmt->bind_param("ss", $token, $name);
            $stmt->execute();
            if ($stmt->errno) {
                print "error: " . $stmt->error;
                exit;
            }
            print "succesfully logged in.";
            $stmt->close();
        } else {
            print "error: " . $con->error;
            exit;
 public function apiManage($edit = 0)
 {
     $this->viewBuilder()->layout("ajax");
     $this->render(false);
     $name = $this->request->data("name");
     $email = $this->request->data("email");
     $access_level = $this->request->data("access_level");
     $password = $this->request->data("password");
     $password_confirm = $this->request->data("password_confirm");
     $salt = uniqid(mt_rand(), true);
     /*$name = "Test2";
     		$email = "*****@*****.**";
     		$access_level = 2;
     		$password = "******";
     		$password_confirm = "123";*/
     $table = TableRegistry::get("Users");
     if ($password != $password_confirm) {
         echo json_encode(["status" => "400", "response" => "Could not save 3"]);
         return;
     }
     $entity = null;
     if ($edit == 0) {
         $entity = $table->newEntity(["name" => $name, "email" => $email, "password" => pbkdf2("sha256", $password, $salt), "salt" => $salt, 'date_created' => Time::createFromTimestamp(time())]);
     } else {
         $entity = $table->find()->where(["id" => $edit])->all();
         if ($entity->count() == 0) {
             echo json_encode(["status" => "400", "response" => "Could not save 1"]);
             return;
         } else {
             $entity = $entity->first();
             $entity->name = $name;
             $entity->email = $email;
             if ($password != "") {
                 $entity->password = pbkdf2("sha256", $password, $salt);
                 $entity->salt = $salt;
             }
         }
     }
     if ($table->save($entity)) {
         if ($edit == 0) {
             if ($access_level > 0) {
                 $assignment = TableRegistry::get("StaffAssignments")->newEntity(["user_id" => $entity->id, "theater_id" => $this->adminTheater, "access_level" => $access_level]);
                 TableRegistry::get("StaffAssignments")->save($assignment);
             }
         } else {
             $assignment = TableRegistry::get("StaffAssignments")->find()->where(["user_id" => $entity->id])->all();
             if ($assignment->count() > 0) {
                 $assignment = $assignment->first();
                 $assignment->access_level = $access_level;
                 TableRegistry::get("StaffAssignments")->save($assignment);
             } else {
                 $assignment = TableRegistry::get("StaffAssignments")->newEntity(["user_id" => $entity->id, "theater_id" => $this->adminTheater, "access_level" => $access_level]);
                 TableRegistry::get("StaffAssignments")->save($assignment);
             }
         }
         echo json_encode(["status" => "200", "response" => "Saved"]);
         return;
     } else {
         echo json_encode(["status" => "400", "response" => "Could not save"]);
         return;
     }
 }
     break;
 case 'change_password':
     //First check if user has entered correct old password
     $q = $dbh->prepare("SELECT id,password FROM cm_users WHERE id = :id AND password = :pword");
     $salt = CC_SALT;
     $hash = pbkdf2($_POST['current_pword'], $salt, 1000, 32);
     $pass = base64_encode($hash);
     $data = array('id' => $_POST['id'], 'pword' => $pass);
     $q->execute($data);
     if ($q->rowCount() < 1) {
         $return = array('error' => true, 'message' => 'Your old password is wrong.');
         echo json_encode($return);
         die;
     } else {
         $q = $dbh->prepare("UPDATE cm_users SET password = :new_pass WHERE id = :id");
         $new_hash = pbkdf2($_POST['new_pword'], $salt, 1000, 32);
         $new_pass = base64_encode($new_hash);
         $data = array('id' => $_POST['id'], 'new_pass' => $new_pass);
         $q->execute($data);
     }
     $error = $q->errorInfo();
     break;
 case 'change_picture':
     //Not yet implemented.  Admin must change picture now.
     break;
 case 'change_private_key':
     $new_key = genKey();
     $q = $dbh->prepare('UPDATE cm_users SET private_key = :private_key WHERE id = :id');
     $data = array('private_key' => $new_key, 'id' => $_POST['id']);
     $q->execute($data);
     $error = $q->errorInfo();
    # Derived key
    # Create key
    for ($block = 1; $block <= $kb; $block++) {
        # Initial hash for this block
        $ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
        # Perform block iterations
        for ($i = 1; $i < $c; $i++) {
            # XOR each iterate
            $ib ^= $b = hash_hmac($a, $b, $p, true);
        }
        $dk .= $ib;
        # Append iterated block
    }
    # Return derived key of correct length
    return substr($dk, 0, $kl);
}
if (isset($_POST['key'])) {
    // Make sure salt is 8 bytes length
    $key = pbkdf2($_POST['passphrase'], $_POST['salt'], $_POST['iterations'], $_POST['keysize']);
    //$text = "yamnuska"; // test plain text
    $text = $_POST['key'];
    $iv = $_POST['initvector'];
    if (isset($_POST['Decrypt'])) {
        // Use the output from above. This also works with Windows encrypted output and strips the padded characters
        $encrypted = $text;
        echo "Decrypted: <input type=\"text\" size=\"60\" value=\"" . rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "") . "\"><br/>";
    } else {
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
        echo "Encrypted: <input type=\"text\" size=\"60\" value=\"" . base64_encode($crypttext) . "\"><br/>";
    }
}
function create_hash($password)
{
    $salt = base64_encode(mcrypt_create_iv(PBKDF2_SALT_BYTE_SIZE, MCRYPT_DEV_URANDOM));
    return TAG . SEPARATOR . PBKDF2_HASH_ALGORITHM . SEPARATOR . PBKDF2_ITERATIONS . SEPARATOR . $salt . SEPARATOR . base64_encode(pbkdf2(PBKDF2_HASH_ALGORITHM, $password, $salt, PBKDF2_ITERATIONS, PBKDF2_HASH_BYTE_SIZE, true));
}
/** Hashes can not be relied on being the same twice */
function create_hash($password)
{
    // format: algorithm:iterations:salt:hash
    $salt = base64_encode(mcrypt_create_iv(PBKDF2_SALT_BYTE_SIZE, MCRYPT_DEV_URANDOM));
    return "derp" . PBKDF2_HASH_ALGORITHM . ":" . PBKDF2_ITERATIONS . ":" . $salt . ":" . base64_encode(pbkdf2(PBKDF2_HASH_ALGORITHM, $password, $salt, PBKDF2_ITERATIONS, PBKDF2_HASH_BYTE_SIZE, true));
}
Example #23
0
    $q->execute();
    $nu = $q->fetch(PDO::FETCH_ASSOC);
    if ($nu['force_new_password'] == '1') {
        $result = 'yes';
    } else {
        $result = 'no';
    }
    return $result;
}
//Set variables
$update_password = force_new_password($dbh, $_POST['username']);
if ($update_password === 'yes') {
    $password = md5($_POST['password']);
} else {
    $salt = CC_SALT;
    $hash = pbkdf2($_POST['password'], $salt, 1000, 32);
    $password = base64_encode($hash);
}
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($_POST['remember'])) {
    $remember = $_POST['remember'];
}
$user_query = $dbh->prepare("SELECT * FROM cm_users WHERE username = ? AND password = ? LIMIT 1");
$user_query->setFetchMode(PDO::FETCH_OBJ);
$user_query->bindParam(1, $_POST['username']);
$user_query->bindParam(2, $password);
$user_query->execute();
$r = $user_query->fetch();
//Do error handling
if ($user_query->rowCount() < 1) {
    $msg = "Your username or password is incorrect. Please try again";
Example #24
0
function checkLogin($type = "username", $input, $password)
{
    global $con;
    require_once 'pbkdf2.php';
    // Require password hash script
    $pass = mysqli_real_escape_string($con, $password);
    $salt = md5($pass);
    // Create salt
    $password = pbkdf2($pass, $salt);
    // Create hashed password
    $input = mysqli_real_escape_string($con, $input);
    // Check if login type is email or username
    if ($type == "email") {
        $check = mysqli_query($con, "SELECT * FROM users WHERE email='{$input}' AND password='******'");
    } else {
        $check = mysqli_query($con, "SELECT * FROM users WHERE username='******' AND password='******'");
    }
    // If combination gives a result, the login is correct and the function returns true
    // NOTE: if you want to use this for a custom login page, you have to create the sessions yourself (search in posthandler.php for login to see what's required)
    if (mysqli_num_rows($check) == 1) {
        return true;
    } else {
        return false;
    }
}
Example #25
0
 protected function createAuthBlob()
 {
     if ($this->challengeData) {
         $key = pbkdf2('sha1', base64_decode($this->password), $this->challengeData, 16, 20, true);
         $this->inputKey = new KeyStream($key);
         $this->outputKey = new KeyStream($key);
         $this->reader->setKey($this->inputKey);
         //$this->writer->setKey($this->outputKey);
         $phone = $this->dissectPhone();
         $array = $this->phoneNumber . $this->challengeData . time() . static::WHATSAPP_USER_AGENT . " MccMnc/" . str_pad($phone["mcc"], 3, "0", STR_PAD_LEFT) . "001";
         $this->challengeData = null;
         return $this->outputKey->encode($array, 0, strlen($array), false);
     }
     return null;
 }
Example #26
0
         if ($blocked_time == "0") {
             $until = 0;
             // Forever
         } else {
             $until = $time + $blocked_time;
             // Current time with the blocked time added
         }
         mysqli_query($con, "INSERT INTO blocks(time, ip, logs, reason, until)\r\n\t\t\t\t\t\t\t\tVALUES ('{$time}','{$ip}','{$failed}','{$reason}','{$until}')");
     }
     echo "<h5 class='text-center red'>" . $m['blocked'] . "</h5>";
 } else {
     require_once 'pbkdf2.php';
     // Requires password encryption script
     $salt = md5($password);
     // Create salt
     $pass = pbkdf2($password, $salt);
     // Encrypt password
     // Check if the login type is email or username
     if (getSetting("login_with", "text") == "email") {
         $loginname = mysqli_real_escape_string($con, $_POST['email']);
         // Check if the login is case sensitive
         if (getSetting("case_sensitive", "text") == "true") {
             $check = mysqli_query($con, "SELECT * FROM users WHERE BINARY email='{$loginname}' AND password='******'");
         } else {
             $check = mysqli_query($con, "SELECT * FROM users WHERE email='{$loginname}' AND password='******'");
         }
         $getuid = mysqli_query($con, "SELECT * FROM users WHERE email='{$loginname}'");
     } else {
         $loginname = mysqli_real_escape_string($con, $_POST['username']);
         // Check if the login is case sensitive
         if (getSetting("case_sensitive", "text") == "true") {
 public static function Hash($password, $salt = '')
 {
     if (ulUtils::BeginsWith($salt, '{SSHA}')) {
         $salt = substr($salt, 6);
         if ($salt == '') {
             $salt = ulUtils::RandomBytes(24, true);
         }
         return '{SSHA}' . base64_encode(pack('H*', sha1($password . $salt)) . $salt);
     } else {
         if (ulUtils::BeginsWith($salt, '{SHA}')) {
             return '{SHA}' . base64_encode(pack('H*', sha1($password)));
         } else {
             if (ulUtils::BeginsWith($salt, '{SMD5}')) {
                 $salt = substr($salt, 6);
                 if ($salt == '') {
                     $salt = ulUtils::RandomBytes(24, true);
                 }
                 return '{SMD5}' . base64_encode(pack('H*', md5($password . $salt)) . $salt);
             } else {
                 if (ulUtils::BeginsWith($salt, '{MD5}')) {
                     return '{MD5}' . base64_encode(pack('H*', md5($password)));
                 } else {
                     if (ulUtils::BeginsWith($salt, '{CRYPT}')) {
                         $salt = substr($salt, 7);
                         if ($salt == '') {
                             $salt = self::BCryptSalt();
                         }
                         // We must not preprocess here to stay compatible with other applications
                         return '{CRYPT}' . crypt($password, $salt);
                     } else {
                         if (ulUtils::BeginsWith($salt, '{PBKDF2}')) {
                             $hash_bytes = 96;
                             $hash_algo = UL_HMAC_FUNC;
                             $hash_rounds = pow(2, UL_PWD_ROUNDS);
                             $salt = substr($salt, 8);
                             if ($salt == '') {
                                 $salt = ulUtils::RandomBytes(16, true);
                             } else {
                                 $parts = explode(':', $salt);
                                 $hash_algo = $parts[0];
                                 $hash_rounds = $parts[1];
                                 $salt = $parts[2];
                             }
                             // We must not preprocess here to stay compatible with other applications
                             return '{PBKDF2}' . $hash_algo . ':' . $hash_rounds . ':' . $salt . ':' . base64_encode(pbkdf2($hash_algo, $password, $salt, $hash_rounds, $hash_bytes, true));
                         } else {
                             // For compatibility with older versions, an empty string is the same as '{BCRYPT}'
                             if (ulUtils::BeginsWith($salt, '{BCRYPT}')) {
                                 $salt = substr($salt, 8);
                             }
                             if ($salt == '') {
                                 $salt = self::BCryptSalt();
                             }
                             return crypt(self::PreProcess($password), $salt);
                         }
                     }
                 }
             }
         }
     }
 }
Example #28
0
    }
    return substr($output, 0, $key_length);
}
function pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen)
{
    $last = $salt . chr(($i >> 24) % 256) . chr(($i >> 16) % 256) . chr(($i >> 8) % 256) . chr($i % 256);
    $xorsum = "";
    for ($r = 0; $r < $count; $r++) {
        $u = hash_hmac($algorithm, $last, $password, true);
        $last = $u;
        if (empty($xorsum)) {
            $xorsum = $u;
        } else {
            for ($c = 0; $c < $hLen; $c++) {
                $xorsum[$c] = chr(ord(substr($xorsum, $c, 1)) ^ ord(substr($u, $c, 1)));
            }
        }
    }
    return bin2hex($xorsum);
}
function genSalt()
{
    return hash("sha256", md5(mt_rand()) . hash("sha1", PASSWORD_PEPPER . time() . mt_rand()));
}
function genVerificationKey()
{
    return sha1(sha1(mt_rand()) . substr(md5(mt_rand()), 12));
}
define('SALT', 'f2d8419c011b0afe33d7468c24dd476733589abaaa75ad0eda9723732ff612fc');
echo pbkdf2("password", SALT);
Example #29
0
function hash_password($password, $salt = null)
{
    $salt = isset($salt) ? $salt : gen_salt();
    $hash_password = pbkdf2('SHA256', $password, $salt, 8000, 512);
    return array($hash_password, $salt);
}
 public function process()
 {
     $method = $this->request->data("payment-method");
     $name = "";
     if ($method == "credit") {
         $name = $this->request->data("card-name");
     } else {
         $name = $this->request->data("name");
     }
     // Get the table ready
     $table = TableRegistry::get("CartItems");
     $ticketTable = TableRegistry::get("Tickets");
     // Select the contents of the user's cart
     $cart = $table->find()->where(["CartItems.cart_id" => $this->Cookie->read("ta_cart_id")])->contain(["Performances", "Performances.Plays", "Performances.Theaters", "Seats", "Seats.Rows", "Seats.Rows.Sections", "Seasons", "Seasons.Theaters"])->all();
     // fetch account info
     $account_name = $this->request->data("account_name");
     $account_email = $this->request->data("account_email");
     $account_password = $this->request->data("account_password");
     $account_password_confirm = $this->request->data("account_password_confirm");
     // fetch address info
     $street = $this->request->data("account_address");
     $city = $this->request->data("account_city");
     $state = $this->request->data("account_state");
     $country = $this->request->data("account_country");
     $zip = $this->request->data("account_zipcode");
     $phone = $this->request->data("account_phone");
     // Perform account management operations
     if ($this->loggedIn && $street != null && $street != "") {
         // Update account with address
         $this->user->street = $street;
         $this->user->city = $city;
         $this->user->state = $state;
         $this->user->country = $country;
         $this->user->zip = $zip;
         $this->user->phone_number = $phone;
         TableRegistry::get("Users")->save($this->user);
     } else {
         if ($account_name != null && $account_name != "") {
             // Make sure the password and confirmation match
             if ($account_password != $account_password_confirm) {
                 $this->Flash->set("The password you entered does not match the confirmation.", ['element' => 'error']);
                 return $this->redirect("/checkout/");
             }
             // Generate the salt
             $salt = uniqid(mt_rand(), true);
             $tbl = TableRegistry::get("Users");
             // Create the new account
             $user = $tbl->newEntity(["name" => $account_name, "email" => $account_email, "password" => pbkdf2("sha256", $account_password, $salt), "salt" => $salt, "street" => $street, "city" => $city, "state" => $state, "country" => $country, "zip" => $zip, "phone_number" => $phone]);
             // Save the user
             $tbl->save($user);
             // Log the new user in
             $key = $user->makeKey();
             $this->Cookie->write('ta_login_id', $user->id);
             $this->Cookie->write('ta_login_email', $user->email);
             $this->Cookie->write('ta_login_key', $key);
         }
     }
     // Redirect if the cart is empty
     if ($cart->count() < 1) {
         return $this->redirect("/cart/");
     }
     $purchase_id = uniqid("", true) . "." . dechex(mt_rand(0, 9999999999));
     $success = true;
     // For each item in the cart
     foreach ($cart as $item) {
         if ($item->season_id == 0) {
             // Check to see whether this ticket was already purchased
             if (!$item->seat->isAvailablePerformance(TableRegistry::get("Performances")->find()->where(["Performances.id" => $item->performance_id])->contain(["Seasons"])->all()->first())) {
                 // Delete the ticket from the cart
                 $table->delete($item);
                 // Display an error to the user
                 $this->Flash->set("The seat " . $item->seat->row->section->code . $item->seat->row->code . "-" . $item->seat->code . " has already been taken.", ['element' => 'error']);
                 // Redirect back to the view cart page
                 return $this->redirect("/cart/");
             }
             // Create the ticket
             $ticket = $ticketTable->newEntity(["theater_id" => $item->performance->theater->id, "section_id" => $item->seat->row->section->id, "row_id" => $item->seat->row->id, "seat_id" => $item->seat->id, "status" => "paid", "customer_id" => $item->loggedIn ? $item->user->id : 0, "customer_name" => $item->loggedIn ? $item->user->name : $name, "ticket_number" => bin2hex($item->performance_id . ":" . $item->seat->id), "performance_id" => $item->performance_id, "season_ticket" => "0", "season_year" => date("Y"), "purchase_id" => $purchase_id]);
             // Save it to the database
             $success = $ticketTable->save($ticket) && $success;
             // Delete the purchase from the user's cart
             $table->delete($item);
         } else {
             // Check to see whether this season ticket was already purchased
             if (!$item->seat->isAvailableSeason(TableRegistry::get("Seasons")->find()->where(["Seasons.id" => $item->season_id])->all()->first())) {
                 // Delete the ticket from the cart
                 $table->delete($item);
                 // Display an error to the user
                 $this->Flash->set("The seat " . $item->seat->row->section->code . $item->seat->row->code . "-" . $item->seat->code . " has already been taken.", ['element' => 'error']);
                 // Redirect back to the view cart page
                 return $this->redirect("/cart/");
             }
             // Create the ticket
             $ticket = $ticketTable->newEntity(["theater_id" => $item->season->theater->id, "section_id" => $item->seat->row->osection->id, "row_id" => $item->seat->oow->id, "seat_id" => $item->seat->id, "status" => "paid", "customer_id" => $item->loggedIn ? $item->user->id : 0, "customer_name" => $item->loggedIn ? $item->user->name : $name, "ticket_number" => bin2hex($item->season_id . ":" . $item->seat->id), "season_id" => $item->season_id, "purchase_id" => $purchase_id]);
             // Save it to the database
             $success = $ticketTable->save($ticket) && $success;
             // Delete the purchase from the user's cart
             $table->delete($item);
         }
     }
     if ($success) {
         return $this->redirect("/checkout/success/{$purchase_id}/");
     } else {
         return $this->redirect("/checkout/");
     }
 }