Skip to content

Instantly share code, notes, and snippets.

@BlaM
Last active January 27, 2023 13:01
Show Gist options
  • Save BlaM/f3a9d535963900d1fbddc890c66f3891 to your computer and use it in GitHub Desktop.
Save BlaM/f3a9d535963900d1fbddc890c66f3891 to your computer and use it in GitHub Desktop.
APR1-MD5 encryption method (windows compatible) for Apache .htpasswd
<?php
// APR1-MD5 encryption method (windows compatible)
// https://gist.github.com/BlaM/f3a9d535963900d1fbddc890c66f3891
//
// 2019-04-09 - https://github.com/BlaM - $salt
// 2022-03-04 - https://github.com/BlaM - fix php7 deprecation warning
// 2023-01-11 - https://github.com/BlaM and https://github.com/alecos71 - prepare for php8 sunset of str_shuffle
function crypt_apr1_md5($plainpasswd, $salt = null) {
if (empty($salt)) {
$chars = 'abcdefghijklmnopqrstuvwxyz012345689';
$length = 8;
if (function_exists('random_int')) {
// PHP 7+
$salt = '';
for ($i = 0; $i < $length; $i++) {
$pos = random_int(0, strlen($chars) -1);
$salt .= substr($chars, $pos, 1);
}
} else if (function_exists('str_shuffle')) {
// PHP 4-8
$salt = substr(str_shuffle($chars), 0, $length);
} else {
throw new Exception('Not implemented');
}
} elseif (substr($salt, 0, 6) == '$apr1$') {
$salt = explode('$', $salt);
$salt = $salt[2];
}
$tmp = "";
$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) : substr($plainpasswd, 0, 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));
}
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)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return "$"."apr1"."$".$salt."$".$tmp;
}
@alecos71
Copy link

Well done!

@alecos71
Copy link

Please, pay attention to this:

Apache in Windows requires the salt, without fails to authenticate. The rest is OK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment