BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
187 lines · 9.7 KB · download this file
package BlowfishCMS;
# A small QR code encoder (byte mode, error correction level M, versions
# 1–10: up to 213 bytes), for showing an authenticator app its key. Drawn on
# the server as SVG, so the key never leaves the site. Follows ISO/IEC 18004.
use v5.36;
use Encode ();
# Per version at level M: error-correction codewords per block, then
# [number of blocks, data codewords per block] for each group.
# How a QR code works, briefly. It's a square grid of dark and light modules.
# Fixed patterns let a camera find and line it up (the three big corner
# squares, the dotted "timing" lines and small alignment squares). The rest
# holds the data as bits, plus extra "error correction" bytes computed from
# it, so a code that's partly dirty or blurred still reads. A "version" is a
# size (version 1 is 21x21 modules, each version adds 4), and level M means
# about 15% of the code can be damaged. The data is XOR-ed with one of eight
# "mask" patterns, chosen so the code has no confusing large blobs or
# finder-like shapes; a small "format" area says which mask and level.
#
# These tables come from the standard: how each version's data is split into
# blocks, and where its alignment patterns sit.
my %qr_blocks=(1=>[10,[1,16]],2=>[16,[1,28]],3=>[26,[1,44]],4=>[18,[2,32]],5=>[24,[2,43]],
6=>[16,[4,27]],7=>[18,[4,31]],8=>[22,[2,38],[2,39]],9=>[22,[3,36],[2,37]],10=>[26,[4,43],[1,44]]);
my %qr_align=(2=>[6,18],3=>[6,22],4=>[6,26],5=>[6,30],6=>[6,34],7=>[6,22,38],8=>[6,24,42],9=>[6,26,46],10=>[6,28,50]);
# Arithmetic for the error correction is in a "Galois field" of 256 values,
# where adding is XOR and multiplying is done with these log and exponent
# tables (0x11d is the field's defining polynomial).
my (@qr_exp,@qr_log);
{my $x=1;for my $i (0..254) {$qr_exp[$i]=$x;$qr_log[$x]=$i;$x<<=1;$x^=0x11d if $x & 0x100} $qr_exp[$_]=$qr_exp[$_-255] for 255..511}
# Multiplies two numbers in that field.
sub qr_mul ($a,$b) { return $a && $b ? $qr_exp[$qr_log[$a]+$qr_log[$b]] : 0 }
# Reed–Solomon error-correction codewords for one block.
# Reed-Solomon error correction: builds the generator polynomial for $n
# correction bytes, then divides the data by it; the remainder is the
# correction bytes.
sub qr_ec ($data,$n) {
my @gen=(1);
for my $i (0..$n-1) {
my @next=(0) x (@gen+1);
for my $j (0..$#gen) {$next[$j]^=$gen[$j];$next[$j+1]^=qr_mul($gen[$j],$qr_exp[$i])}
@gen=@next;
}
my @rem=(0) x $n;
for my $byte (@$data) {
my $factor=$byte ^ shift @rem;push @rem,0;
$rem[$_]^=qr_mul($gen[$_+1],$factor) for 0..$n-1;
}
return @rem;
}
# How many data bytes a version holds at level M.
sub qr_capacity ($v) { my ($ec,@groups)=@{$qr_blocks{$v}};my $n=0;$n+=$_->[0]*$_->[1] for @groups;return $n }
# The final codeword sequence: data split into blocks, interleaved, then their error correction.
# The bytes to place in the grid: a mode marker (0100 = bytes), the length,
# the data, a terminator, padding to a whole byte, then the standard filler
# bytes (0xEC, 0x11) up to the capacity. The data is split into blocks, each
# gets its correction bytes, and the blocks are interleaved byte by byte, so
# a damaged patch hurts several blocks a little rather than one a lot.
sub qr_codewords ($bytes,$v) {
my @bits=(0,1,0,0);
my $countbits=$v<10 ? 8 : 16;
push @bits,split //,sprintf("%0${countbits}b",scalar @$bytes);
push @bits,split //,sprintf('%08b',$_) for @$bytes;
my $cap=qr_capacity($v)*8;
push @bits,(0) x (($cap-@bits)<4 ? $cap-@bits : 4);
push @bits,0 while @bits % 8;
my @data=map {oct('0b'.join '',@bits[$_*8..$_*8+7])} 0..@bits/8-1;
my $pad=0;push @data,($pad++ % 2 ? 0x11 : 0xEC) while @data<qr_capacity($v);
my ($ec,@groups)=@{$qr_blocks{$v}};my (@blocks,@ecs);
for my $g (@groups) {for (1..$g->[0]) {my @b=splice @data,0,$g->[1];push @blocks,\@b;push @ecs,[qr_ec(\@b,$ec)]}}
my @out;my $longest=0;$longest=@$_>$longest ? scalar @$_ : $longest for @blocks;
for my $i (0..$longest-1) {push @out,$_->[$i] for grep {$i<@$_} @blocks}
for my $i (0..$ec-1) {push @out,$_->[$i] for @ecs}
return @out;
}
# A BCH code (another error-correcting code) for the small format and version
# areas: the value followed by the remainder of dividing it by $poly.
sub qr_bch ($value,$poly,$bits) {
my $plen=length sprintf('%b',$poly);my $v=$value<<($plen-1);
while ((my $l=length sprintf('%b',$v))>=$plen) {$v^=$poly<<($l-$plen)}
return ($value<<($plen-1))|$v;
}
# The standard's eight mask patterns: whether mask $m flips the module at
# row $r, column $c.
sub qr_mask_bit ($m,$r,$c) {
return (($r+$c)%2==0) if $m==0;return ($r%2==0) if $m==1;return ($c%3==0) if $m==2;
return (($r+$c)%3==0) if $m==3;return ((int($r/2)+int($c/3))%2==0) if $m==4;
return ((($r*$c)%2+($r*$c)%3)==0) if $m==5;return (((($r*$c)%2+($r*$c)%3)%2)==0) if $m==6;
return (((($r+$c)%2+($r*$c)%3)%2)==0);
}
# Penalty score of a finished matrix (lower is easier to read).
# Scores a finished grid by the standard's rules (long runs of one colour,
# 2x2 blocks, finder-like patterns, too much dark or light); the mask with
# the lowest score is used.
sub qr_penalty ($m) {
my $n=@$m;my $p=0;
for my $line ((map {my $r=$_;[map {$m->[$r][$_]} 0..$n-1]} 0..$n-1),(map {my $c=$_;[map {$m->[$_][$c]} 0..$n-1]} 0..$n-1)) {
my $run=1;
for my $i (1..$n) {
if ($i<$n && $line->[$i]==$line->[$i-1]) {$run++}
else {$p+=$run-2 if $run>=5;$run=1}
}
my $s=join '',@$line;
$p+=40 while $s =~ /(?=10111010000|00001011101)/g;
}
for my $r (0..$n-2) {for my $c (0..$n-2) {my $v=$m->[$r][$c];$p+=3 if $v==$m->[$r][$c+1] && $v==$m->[$r+1][$c] && $v==$m->[$r+1][$c+1]}}
my $dark=0;$dark+=$_ for map {@$_} @$m;
$p+=10*int(abs($dark*100/($n*$n)-50)/5);
return $p;
}
# The matrix (rows of 0/1) for TEXT, in the smallest version that fits.
# Builds the grid for a text: picks the smallest version that fits, draws
# the fixed patterns and marks them (and the format areas) as taken, then
# lays the data bits in two-module-wide columns zigzagging up and down from
# the bottom right, skipping taken modules and the timing column. Finally it
# tries all eight masks with the format information written in, and keeps
# the one with the lowest penalty.
sub qr_matrix ($text,$mask=undef) {
my @bytes=unpack 'C*',Encode::encode('UTF-8',$text);
my ($v)=grep {qr_capacity($_)*8 >= 4+($_<10?8:16)+8*@bytes} 1..10;
die "That's too long for a QR code here.\n" unless $v;
my $n=17+4*$v;my (@m,@fixed);
for my $r (0..$n-1) {$m[$r]=[(0) x $n];$fixed[$r]=[(0) x $n]}
my $set=sub ($r,$c,$d) {$m[$r][$c]=$d?1:0;$fixed[$r][$c]=1};
for my $at ([0,0],[0,$n-7],[$n-7,0]) {
my ($r0,$c0)=@$at;
for my $r (-1..7) {for my $c (-1..7) {
my ($rr,$cc)=($r0+$r,$c0+$c);next if $rr<0 || $cc<0 || $rr>=$n || $cc>=$n;
my $in=$r>=0 && $r<=6 && $c>=0 && $c<=6;
$set->($rr,$cc,$in && ($r==0 || $r==6 || $c==0 || $c==6 || ($r>=2 && $r<=4 && $c>=2 && $c<=4)));
}}
}
for my $i (8..$n-9) {$set->(6,$i,$i%2==0);$set->($i,6,$i%2==0)}
if (my $pos=$qr_align{$v}) {
my ($lo,$hi)=($pos->[0],$pos->[-1]);
for my $r (@$pos) {for my $c (@$pos) {
# Not in the three corners the finder patterns already take.
next if ($r==$lo && $c==$lo) || ($r==$lo && $c==$hi) || ($r==$hi && $c==$lo);
for my $dr (-2..2) {for my $dc (-2..2) {$set->($r+$dr,$c+$dc,abs($dr)==2 || abs($dc)==2 || ($dr==0 && $dc==0))}}
}}
}
$set->($n-8,8,1);
# Reserve the format (and version) areas; they're written after masking.
for my $i (0..8) {$fixed[8][$i]=1;$fixed[$i][8]=1}
for my $i (0..7) {$fixed[8][$n-1-$i]=1;$fixed[$n-1-$i][8]=1}
if ($v>=7) {for my $i (0..5) {for my $j (0..2) {$fixed[$i][$n-11+$j]=1;$fixed[$n-11+$j][$i]=1}}}
my @bits=map {split //,sprintf('%08b',$_)} qr_codewords(\@bytes,$v);
my $k=0;my $up=1;
for (my $c=$n-1;$c>0;$c-=2) {
$c-- if $c==6;
for my $i (0..$n-1) {
my $r=$up ? $n-1-$i : $i;
for my $cc ($c,$c-1) {next if $fixed[$r][$cc];$m[$r][$cc]=$k<@bits ? $bits[$k] : 0;$k++}
}
$up=!$up;
}
my $finish=sub ($mask) {
my @x=map {[@$_]} @m;
for my $r (0..$n-1) {for my $c (0..$n-1) {$x[$r][$c]^=1 if !$fixed[$r][$c] && qr_mask_bit($mask,$r,$c)}}
my $format=qr_bch((0b00<<3)|$mask,0x537,15) ^ 0x5412;
my @f=map {($format>>$_)&1} 0..14;
for my $i (0..5) {$x[$i][8]=$f[$i]}
$x[7][8]=$f[6];$x[8][8]=$f[7];$x[8][7]=$f[8];
for my $i (9..14) {$x[8][14-$i]=$f[$i]}
for my $i (0..7) {$x[8][$n-1-$i]=$f[$i]}
for my $i (8..14) {$x[$n-15+$i][8]=$f[$i]}
$x[$n-8][8]=1;
if ($v>=7) {
my $vb=qr_bch($v,0x1f25,18);
for my $i (0..17) {my $b=($vb>>$i)&1;my ($a,$bb)=(int($i/3),$n-11+$i%3);$x[$a][$bb]=$b;$x[$bb][$a]=$b}
}
return \@x;
};
return $finish->($mask) if defined $mask;
my ($best,$score);
for my $mk (0..7) {my $x=$finish->($mk);my $s=qr_penalty($x);($best,$score)=($x,$s) if !defined $score || $s<$score}
return $best;
}
# An SVG of the code, with the quiet zone around it.
# The grid as an SVG picture: one tiny square per dark module, with a white
# "quiet zone" of four modules around it, which scanners need.
sub qr_svg ($text,$label='QR code') {
my $m=qr_matrix($text);my $n=@$m;my $size=$n+8;my $path='';
for my $r (0..$n-1) {for my $c (0..$n-1) {$path.='M'.($c+4).' '.($r+4).'h1v1h-1z' if $m->[$r][$c]}}
return '<svg class="qr-code" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 '.$size.' '.$size.'" role="img" aria-label="'.h($label).'" shape-rendering="crispEdges"><rect width="'.$size.'" height="'.$size.'" fill="#fff"/><path fill="#000" d="'.$path.'"/></svg>';
}
1;