67 lines
2 KiB
PHP
67 lines
2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
class Hash
|
||
|
|
{
|
||
|
|
|
||
|
|
/**
|
||
|
|
*
|
||
|
|
* @param string $algo The algorithm (md5, sha1, whirlpool, etc)
|
||
|
|
* @param string $data The data to encode
|
||
|
|
* @param string $salt The salt (This should be the same throughout the system probably)
|
||
|
|
* @return string The hashed/salted data
|
||
|
|
*/
|
||
|
|
public static function create($algo, $data, $salt)
|
||
|
|
{
|
||
|
|
$context = hash_init($algo, HASH_HMAC, $salt);
|
||
|
|
hash_update($context, $data);
|
||
|
|
|
||
|
|
return hash_final($context);
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function createApi(){
|
||
|
|
$key = implode('-', str_split(substr(strtolower(md5(microtime().rand(1000, 9999))), 0, 30), 6));
|
||
|
|
return $key;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function formData(){
|
||
|
|
$key = implode('-', str_split(substr(strtolower(md5(microtime().rand(1000, 9999))), 0, 15), 5));
|
||
|
|
return $key;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Normalize a date-of-birth string to YYYYMMDD for consistent hashing.
|
||
|
|
* Handles: YYYY-MM-DD (from HTML date input), MM/DD/YYYY, MMDDYYYY, YYYYMMDD.
|
||
|
|
*/
|
||
|
|
public static function normalizeDob($dob) {
|
||
|
|
if (empty($dob)) return '';
|
||
|
|
$dob = trim((string)$dob);
|
||
|
|
|
||
|
|
// Already YYYYMMDD
|
||
|
|
if (preg_match('/^\d{8}$/', $dob)) return $dob;
|
||
|
|
|
||
|
|
// YYYY-MM-DD (HTML date input)
|
||
|
|
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob)) {
|
||
|
|
return str_replace('-', '', $dob);
|
||
|
|
}
|
||
|
|
|
||
|
|
// MM/DD/YYYY
|
||
|
|
if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $dob)) {
|
||
|
|
$d = \DateTime::createFromFormat('m/d/Y', $dob);
|
||
|
|
return $d ? $d->format('Ymd') : $dob;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Fallback
|
||
|
|
$ts = strtotime($dob);
|
||
|
|
return $ts ? date('Ymd', $ts) : $dob;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Create a stable consumer profile ID from DOB + SSN.
|
||
|
|
* Returns first 32 chars of HMAC-SHA256.
|
||
|
|
*/
|
||
|
|
public static function createConsumerProfileId($dob, $ssn, $salt) {
|
||
|
|
$normalized = self::normalizeDob($dob) . preg_replace('/[^0-9]/', '', $ssn);
|
||
|
|
return substr(hash_hmac('sha256', $normalized, $salt), 0, 32);
|
||
|
|
}
|
||
|
|
}
|