Skip to content

Instantly share code, notes, and snippets.

@mwgamera
Last active December 26, 2015 00:09
Show Gist options
  • Save mwgamera/7061619 to your computer and use it in GitHub Desktop.
Save mwgamera/7061619 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
# Encrypt the penguin with AES-ECB. I/O in PPM (P6) format.
# klg, Oct 2013
use strict;
use bytes;
use Crypt::Rijndael;
my $src = do { local $/; <> };
my $key = pack 'H*', '6b6c67323031332cecceab7fffe4391d';
my $WS = qr/\s+|\s*#[^\n]*\n/;
die "Invalid PPM (P6) image"
unless $src =~ m/^(P6$WS(\d+)$WS(\d+)$WS(\d+)\s)/;
my ($width, $height) = ($2, $3);
die "Color depth not supported" unless $4 <= 255;
$src = substr $src, length $1, 3 * $width * $height;
printf "P6\n# AES-%u-ECB K=<%s>\n", 8*length$key, unpack 'H*', $key;
printf "%u %u 255\n", $width, $height;
print Crypt::Rijndael->new($key)->encrypt($src); # ->decrypt($src);
exit;
#!/usr/bin/env perl
# Find "nice" key for AES-ECB-encrypted penguins
# klg, Oct 2013
use strict;
use bytes;
use Crypt::Random::Seed;
use Math::Random::ISAAC;
use Crypt::Rijndael;
use Graphics::ColorObject qw/RGB255_to_RGB RGB_to_Lab/;
use List::Util 'sum';
my $prefix = 'klg2013,';
my $rng = Math::Random::ISAAC->new(Crypt::Random::Seed->new->random_values(8));
# Average color of raw pixel data
sub avglab($) {
my ($L, $a, $b, $n) = (0, 0, 0, 0);
for (unpack '(a3)*', shift) {
my $c = RGB_to_Lab RGB255_to_RGB [unpack 'C3'];
$n++;
$L += ($c->[0] - $L) / $n;
$a += ($c->[1] - $a) / $n;
$b += ($c->[2] - $b) / $n;
}
return $L, $a, $b;
}
my $BEST = 0;
while (1) {
# Random key
my $key = $prefix . join '', map { chr $rng->irand } 1 .. 16 - length $prefix;
my $ecb = Crypt::Rijndael->new($key);
# 16px @ 24bpp = 3 × 128-bit blocks
my @B = avglab $ecb->encrypt("\x00\x00\x00" x 16);
my @W = avglab $ecb->encrypt("\xff\xff\xff" x 16);
my @T = avglab $ecb->encrypt("\xff\x00\x00" x 16);
my @M = (50, 0, 0);
my $M1 = sum map { ($B[$_]-$M[$_])**2 } 0..2;
my $M2 = sum map { ($W[$_]-$M[$_])**2 } 0..2;
my $E1 = sum map { ($T[$_]-$W[$_])**2 } 0..2;
my $E2 = sum map { ($B[$_]-$W[$_])**2 } 0..2;
my $E3 = ($T[0]-$W[0])**2;
my $X = $E1 + 2*$E3 - $E2 - $M1 - $M2;
if ($X >= $BEST - 100) {
$BEST = $X if $X > $BEST;
my $C = abs($T[0] - $W[0]) / ($T[0] + $W[0]); # contrast
printf "K=<%s> PenguinΔE=%g TextΔE=%g C=%g\n", unpack('H*', $key), sqrt$E2, sqrt$E1, $C;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment