Last active
October 12, 2016 14:48
-
-
Save bduggan/1169b193e6d3a93c9a06ade885a680f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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