#!/usr/bin/perl

use strict;
use warnings;

# Prve dvije DES S-kutije
my @Sbox1=(
    14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7,
     0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8,
     4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0,
    15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13
);

my @Sbox2=(
    15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10,
     3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5,
     0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15,
    13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9
);

our @Sbox=(\@Sbox1, \@Sbox2);

sub S {
    my ($j,$B)=@_; # broj S-kutije i 6-bitni niz
    my $v=($B & 0b100000)>>4 | ($B & 1); # prvi i sesti bit
    my $c=($B & 0b11110)>>1; # srednji bitovi
    return $Sbox[$j][16*$v+$c];
}

my $j=(shift @ARGV)-1; # broj S-kutije
my $E=oct(shift @ARGV); # E
my $EEE=oct(shift @ARGV); # E*
my $CC=oct(shift @ARGV); # C'

my $EE=$E^$EEE; # E'=E xor E*

for (my $B=0; $B<64; $B++) {
    if ((S($j,$B)^S($j,$B^$EE))==$CC) {
	printf "%06b ", $B^$E;
    }
}
print "\n";
