#!/usr/bin/perl

# ( $n, $e, $d ) = gen_RSA_keys( $bits, $e );
#       $bits is the length desired for $n
#          ($p and $q will be half as long)
#       ($e,$n) is the public key
#       ($d,$n) is the private key
#       $p and $q are not returned - they are not used after this.
sub gen_RSA_keys {
    my ( $bits, $e ) = @_;
    use SSLeay;

    my ( $p, $q, $t );

    do {$p = SSLeay::BN::generate_prime( $bits/2, 0 );
        $t = $p - 1;
    } while $t->gcd($e) == 1;

    do {$q = SSLeay::BN::generate_prime( $bits/2, 0 );
        $t = $q - 1;
    } while $t->gcd($e) == 1;

    my $n = $p * $q;
    # ($p-1)*($q-1) == $n - $p - $q + 1
    $t = $n - $p - $q + 1;

    # Make sure that $e is a BN (Big Number).
    $e = $p - $p + $e;

    my $d = $e->mod_inverse( $t );

    return ( $n, $e, $d );
}

my ( $n, $e, $d ) = gen_RSA_keys( 512, 3 );
