Skip to content

Instantly share code, notes, and snippets.

@afk11
Created February 26, 2021 12:36
Show Gist options
  • Save afk11/26be2ca69f34c7480cfbc6151477ff68 to your computer and use it in GitHub Desktop.
Save afk11/26be2ca69f34c7480cfbc6151477ff68 to your computer and use it in GitHub Desktop.
Base32 consistency check brute forcer. Can be given a shard to run over multiple cores.
<?php
/**
* This is a brute force script to test all 8-bit, 16-bit and 32-bit byte strings
* using the new Base32 implementation.
* - first ensure both implementations produce the same encoding
* - then ensure the new implementation can decode the encoding
*
* To spread the work over multiple cores, provide a prefix and bit len:
* eg: Two cores (half CPU time)
* php tester.php 1 1 # bitlen=1, prefix=1
* php tester.php 1 1 # bitlen=1, prefix=0
*
* eg: Four cores (quarter CPU time)
* php tester.php 1 1 # bitlen=2, prefix=00
* php tester.php 1 1 # bitlen=2, prefix=01
* php tester.php 1 1 # bitlen=2, prefix=10
* php tester.php 1 1 # bitlen=2, prefix=11
*
* See the checkIt function for the main operation.
*
* This script refers to 'Base32/Base322', which is
* a copy of an older implementation for cross testing
*/
use Base32\Base32;
use Base32\Base322;
require "vendor/autoload.php";
$bits = 0;
$prefix = 0;
if ($argc > 2) {
$bits = (int) $argv[1];
$prefix = bindec($argv[2]);
}
function checkit($loop, $in, $i) {
echo "loop $loop, $i\n";
echo bin2hex($in).PHP_EOL;
$enc = Base32::encode($in);
$enc2 = Base322::encode($in);
if ($enc != $enc2) {
echo "enc didn't match";
echo "enc=$enc\n";
echo "enc2=$enc2\n";
die();
}
$in2 = Base32::decode($enc);
if ($in != $in2) {
echo "input: ".bin2hex($in).PHP_EOL;
echo "got back: ".bin2hex($in2).PHP_EOL;
die();
}
}
// increment instead of add?
$a = $prefix << (8-$bits);
for ($i = 0; $i < pow(2, 8-$bits); $i++) {
$num = $a | $i;
$in = pack("C", $num);
checkIt('8', $in, $num);
}
$a = $prefix << (16-$bits);
for ($i = 0; $i < pow(2, 16-$bits); $i++) {
$in = pack("n", $a | $i);
checkIt('16', $in, $i);
}
$a = $prefix << (32-$bits);
for ($i = 0; $i < pow(2, 32-$bits); $i++) {
$in = pack("N", $a | $i);
checkIt('32', $in, $i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment