Crypt-Hill
view release on metacpan or search on metacpan
lib/Crypt/Hill.pm view on Meta::CPAN
has 'encrypt_key' => (is => 'rw');
=head1 DESCRIPTION
The Hill cipher is an example of a block cipher. A block cipher is a cipher in
which groups of letters are enciphered together in equal length blocks. The Hill
cipher was developed by Lester Hill & introduced in an article published in 1929.
The L<Crypt::Hill> module is using block size 2.Acceptable characters are A to Z.
=head1 CONSTRUCTOR
The constructor expects one parameter i.e. key to be used in the encryption and
decryption.The key should consists of no more than 4 ALPHABETS.
use strict; use warnings;
use Crypt::Hill;
my $crypt = Crypt::Hill->new({ key => 'DDCF' });
=cut
sub BUILD {
my ($self) = @_;
my $encrypt_key = $self->_encrypt_key;
$self->encrypt_key($encrypt_key);
}
=head1 METHODS
=head2 encode($message)
Encodes the message using the key provided and returns encoded message.
use strict; use warnings;
use Crypt::Hill;
my $crypt = Crypt::Hill->new({ key => 'DDCF' });
my $encoded = $crypt->encode('HELP');
print "Encoded: [$encoded]\n";
=cut
sub encode {
my ($self, $message) = @_;
return $self->_process($self->encrypt_key, $message);
}
=head2 decode($encoded_message)
Decodes the encoded message using the key provided.
use strict; use warnings;
use Crypt::Hill;
my $crypt = Crypt::Hill->new({ key => 'DDCF' });
my $encoded = $crypt->encode('HELP');
my $decoded = $crypt->decode($encoded);
print "Encoded: [$encoded]\n";
print "Decoded: [$decoded]\n";
=cut
sub decode {
my ($self, $message) = @_;
return $self->_process($self->_decrypt_key, $message);
}
#
#
# PRIVATE METHODS
sub _process {
my ($self, $key, $message) = @_;
my @chars = @$CHARSETS;
my $modulos = scalar(@chars);
my $size = $self->block_size;
my $table = $self->table;
my $_message = to_matrix_2_x_1($message, $CHARSETS, $table, $size);
my $result = '';
foreach (@$_message) {
my $_matrix = multiply_mod($key, $_, $modulos);
$result .= sprintf("%s%s", $chars[$_matrix->[0][0]], $chars[$_matrix->[1][0]]);
}
return $result;
}
# convert key to matrix (1x2)
sub _encrypt_key {
my ($self) = @_;
my $table = $self->table;
my $key = $self->key;
die "ERROR: Key should be of length $KEY_LENGTH." unless (length($key) == $KEY_LENGTH);
my $size = $self->block_size;
my $enc_key = to_matrix_1_x_2($key, $CHARSETS, $table, $size);
die "ERROR: Invalid key [$key] supplied." if (get_determinant($enc_key) == 0);
return $enc_key;
}
# descrypt key to matrix (2x2)
sub _decrypt_key {
my ($self) = @_;
my $key = $self->encrypt_key;
my $modulus = scalar(@$CHARSETS);
return inverse_matrix($key, $modulus);
}
=head1 AUTHOR
Mohammad S Anwar, C<< <mohammad.anwar at yahoo.com> >>
=head1 REPOSITORY
( run in 0.911 second using v1.01-cache-2.11-cpan-600a1bdf6e4 )