Skip to content

Instantly share code, notes, and snippets.

@bduggan bduggan/rsa.p6
Last active Oct 12, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.