SATS/lib/cyclic-hash/source/decr.php

101 lines
2.4 KiB
PHP
Raw Normal View History

<?php
require_once __DIR__.'/../../include/const';
/* [1] Function that generates a random secret
=========================================================*/
function generate_secret(){
/* (1) Generate random set */
$charlist = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_';
/* (2) Set useful variables */
$clen = strlen($charlist);
$secret = '';
/* (3) Generate random characters one by one */
for( $i = 0 ; $i < SECRET_SIZE ; $i++ )
$secret .= $charlist[rand(0, $clen - 1)];
/* (4) Return the secret */
return $secret;
}
function cyclichash_decr(){
/* [2] Fetch necessary data
=========================================================*/
/* (1) Fetch secret file */
$secret = @file_get_contents(SECRET_CONF);
/* (2) Check secret file format */
if( !is_string($secret) || !preg_match("/^(.{".SECRET_SIZE."}):(\d+):(.{".SECRET_SIZE."})$/", $secret, $match) ){
// Generate full secret
$secret = generate_secret().':999:'.generate_secret();
// Try to override the secret file
if( @file_put_contents(SECRET_CONF, $secret) ){
slog("Random secret generated successfully", 'cyclic-hash:decr');
return 0;
}else{
slog("Error while generating new random secret", 'cyclic-hash:decr');
return 127;
}
}
/* (3) Extract data */
$key = (string) $match[1];
$depth = (int) $match[2];
$next = (string) $match[3];
/* [3] If can decrement, decrement
=========================================================*/
if( $depth > 1 ){
/* (1) Decrement the depth */
$depth--;
/* (2) Try to override the secret file */
if( @file_put_contents(SECRET_CONF, "$key:$depth:$next") ){
slog("Secret depth decremented to $depth", 'cyclic-hash:decr');
return 0;
}else{
slog("Error while decrementing secret depth", 'cyclic-hash:decr');
return 127;
}
/* [4] If cannot decrement, use new secret and generate next
=========================================================*/
}else{
// Generate new secret
$secret = $next.':999:'.generate_secret();
// Try to override the secret file
if( @file_put_contents(SECRET_CONF, $secret) ){
slog("Random secret generated successfully", 'cyclic-hash:decr');
return 0;
}else{
slog("Error while generating new random secret", 'cyclic-hash:decr');
return 127;
}
}
return 0;
}
echo cyclichash_decr();
?>