Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created April 20, 2012 16:37
Show Gist options
  • Select an option

  • Save jedisct1/2430177 to your computer and use it in GitHub Desktop.

Select an option

Save jedisct1/2430177 to your computer and use it in GitHub Desktop.
webigin token generation
<?php
define('WEBIGIN2_CIPHER', 'aes-128-cfb');
define('WEBIGIN2_CIPHER_BLOCK_SIZE', 16);
define('WEBIGIN2_CIPHER_KEY1', '0123456789ABCDEF');
define('WEBIGIN2_CIPHER_KEY2', 'CAFEBABEDEADBEEF');
define('WEBIGIN2_KV_KEY_SIZE', 8);
function webigin2_base32_encode($str) {
$BASE32_TABLE = '0123456789bcdfghjklmnpqrstuvwxyz';
$out = '';
$i = $j = $v = $bits = 0;
$str_len = strlen($str);
while ($j < $str_len) {
$v |= ord($str[$j++]) << $bits;
$bits += 8;
while ($bits >= 5) {
$out .= $BASE32_TABLE[$v & 31];
$bits -= 5;
$v >>= 5;
}
}
if ($bits > 0) {
$out .= $BASE32_TABLE[$v & 31];
}
return $out;
}
function webigin2_get_opendnscache_token($kv_key) {
$now = time();
$kv_key_len = strlen($kv_key);
assert(WEBIGIN2_CIPHER_BLOCK_SIZE >= $kv_key_len + 4);
$message = $kv_key . pack('N', $now);
$pad_len = WEBIGIN2_CIPHER_BLOCK_SIZE - ($kv_key_len + 4);
$pad = openssl_random_pseudo_bytes($pad_len);
$message_with_pad = $message . $pad;
assert(strlen($message_with_pad) === WEBIGIN2_CIPHER_BLOCK_SIZE);
$iv = openssl_encrypt(str_repeat("\0", WEBIGIN2_CIPHER_BLOCK_SIZE),
WEBIGIN2_CIPHER, WEBIGIN2_CIPHER_KEY1,
TRUE, $message_with_pad);
assert(strlen($iv) === WEBIGIN2_CIPHER_BLOCK_SIZE);
$c = openssl_encrypt($message_with_pad, WEBIGIN2_CIPHER,
WEBIGIN2_CIPHER_KEY2, TRUE, $iv);
return webigin2_base32_encode($iv . $c);
}
/* $kv_key is the key for our memcache-compatible store */
$kv_key = openssl_random_pseudo_bytes(WEBIGIN2_KV_KEY_SIZE);
/*
* $token is the token, so that a query for <token>.<datacenter>.originid.opendns.com
* will be made.
*/
$token = webigin2_get_opendnscache_token($kv_key);
echo $token . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment