Skip to content

Instantly share code, notes, and snippets.

@hnw
Created May 11, 2016 12:33
Show Gist options
  • Save hnw/5964d019be6f28a2dfd5bd5f6311ce9c to your computer and use it in GitHub Desktop.
Save hnw/5964d019be6f28a2dfd5bd5f6311ce9c to your computer and use it in GitHub Desktop.
<?php
echo nsec3hash("434FFFA6F0", "jp", 8), "\n"; // OULDMHVB61HBUBCG40NBLF4UEPS26THV
echo nsec3hash("DEAD", "dnsex.nl", 0), "\n"; // ROCCJAE8BJJU7HN6T7NG3TNM8ACRS87J
echo nsec3hash("DEAD", "a.b.c.example.org", 2), "\n"; // 6LQ07OAHBTOOEU2R9ANI2AT70K5O0RCG
function nsec3hash($salt, $label, $iter) {
$raw_salt = hex2bin($salt);
$label = normalize_rr(strtolower($label));
$hash = sha1($label.$raw_salt, true);
while ($iter--) {
$hash = sha1($hash.$raw_salt, true);
}
return strtoupper(gmp_strval(gmp_init(bin2hex($hash), 16), 32));
}
function normalize_rr($label) {
$ret = preg_replace('/\.+/', '.', ".${label}.");
$ret = preg_replace_callback('/\.([^.]*)/',
function ($matches) {
return chr(strlen($matches[1])).$matches[1];
},
$ret);
return $ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment