How to programmatically build an APR1-MD5 using PHP

时光怂恿深爱的人放手 提交于 2019-11-30 10:10:38

It turns out I made a mistake and this function does in fact create working APR1 htpasswd entries. They do look different to the ones Apache creates but they do work.

Look for existing components that do it on sites like phpclasses.org. One example: http://www.phpclasses.org/browse/package/5066.html.

This might be a bit hacky, but have you considered using the exec() function to call the command that generates the htpasswd ?

Thanks you! It works like a charm.

Just a small comment: The salt can also contain "./" and "A..Z" besides "a..z0..9", so it is the same string as the 'translate-to' string in the last line. And sometimes you want to set the salt in addition, to create reproducable results, like:

function crypt_apr1_md5( $plainpasswd, $salt = '' ) {
$translateTo = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if ( $salt == '' ) { $salt = substr(str_shuffle($translateTo), 0, 8); }

...

$tmp = strtr(strrev(substr(base64_encode($tmp), 2)), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", $translateTo);
return '$apr1$'.$salt.'$'.$tmp;
}

Dmitriy Barybin

See on this:

1:   private function crypt_apr1_md5($plainpasswd) { </br>
7:   for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(o) : $plainpasswd{0}; } </br>
16:  $tmp = ''; </br>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!