1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124:
<?php
namespace CJPGDK\PhpHttpAuth\Hash;
trait Apr1Md5
{
private $base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
private $apr1Md5Alphabet = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
public function getApr1Md5HtpasswdRow($user, $hashedpwd = null)
{
if (is_array($user)) {
return "{$user['username']}:{$user['password']}";
}
return "{$user}:{$hashedpwd}";
}
public function createUserApr1Md5($user, $pwd)
{
return array('username' => $user, 'password' => $this->getApr1Md5Hash($pwd));
}
public function getApr1Md5Hash($plainpasswd, $salt = null)
{
if (is_null($salt)) {
$salt = $this->getApr1Salt(8);
}
$len = strlen($plainpasswd);
$text = $plainpasswd.'$apr1$'.$salt;
$bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
for ($i = $len; $i > 0; $i -= 16) {
$text .= substr($bin, 0, min(16, $i));
}
for ($i = $len; $i > 0; $i >>= 1) {
$text .= ($i & 1) ? chr(0) : $plainpasswd{0};
}
$bin = pack("H32", md5($text));
for ($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $plainpasswd : $bin;
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $plainpasswd;
}
$new .= ($i & 1) ? $bin : $plainpasswd;
$bin = pack("H32", md5($new));
}
$tmp=null;
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if ($j == 16) {
$j = 5;
}
$tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
}
$tmp = chr(0).chr(0).$bin[11].$tmp;
$tmp = strtr(strrev(substr(base64_encode($tmp), 2)), $this->base64Alphabet, $this->apr1Md5Alphabet);
return "\$apr1\${$salt}\${$tmp}";
}
private function getApr1Salt($length = 8)
{
$alphabet = $this->apr1Md5Alphabet;
$salt = '';
for ($i = 0; $i < intval($length); $i++) {
$orpb = openssl_random_pseudo_bytes(1);
$offset = hexdec(bin2hex($orpb)) % 64;
$salt .= $alphabet[$offset];
}
return $salt;
}
public function matchApr1Md5Hash($plain, $hash)
{
if (strpos($hash, '$apr1') === 0) {
$passParts = explode('$', $hash);
$salt = $passParts[2];
$hashed = $this->getApr1Md5Hash($plain, $salt);
return $hashed == $hash;
}
return false;
}
}