Skip to content

Instantly share code, notes, and snippets.

@bduggan
Last active October 12, 2016 14:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bduggan/1169b193e6d3a93c9a06ade885a680f9 to your computer and use it in GitHub Desktop.
Save bduggan/1169b193e6d3a93c9a06ade885a680f9 to your computer and use it in GitHub Desktop.
sub random-prime(:$digits) {
repeat { $_ = (10**$digits .. (10**($digits+1))).pick } until .is-prime;
return $_;
}
sub encrypt(:$message, :$key) {
return expmod($message,$key[0],$key[1])
}
sub decrypt(:$message, :$key) {
return expmod($message,$key[0],$key[1])
}
my $q = random-prime(:110digits);
my $p = random-prime(:110digits);
my $pq = $p * $q;
my $phi = ($p-1) * ($q-1);
my $k;
repeat {
$k = (1..$pq).pick;
} until $k gcd $phi == 1;
my $inverse = expmod($k, -1, $phi);
my $public = [ $k , $pq ];
my $private =[ $inverse, $pq ];
use Test;
for 1..100 {
my $plain = (1..$pq).pick;
my $encrypted = encrypt(message => $plain, key => $public);
my $decrypted = decrypt(message => $encrypted, key => $private);
ok $decrypted==$plain, "decrypted message";
}
done-testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment