1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: math.miller-rabin kernel math math.functions namespaces
7 ! The private key is the only secret.
9 ! p,q are two random primes of numbits/2
13 ! private = public modinv phi
15 TUPLE: rsa modulus private-key public-key ;
21 : public-key 65537 ; inline
23 : rsa-primes ( numbits -- p q )
24 2/ 2 unique-primes first2 ;
26 : modulus-phi ( numbits -- n phi )
27 #! Loop until phi is not divisible by the public key.
28 dup rsa-primes [ * ] 2keep
30 dup public-key gcd nip 1 = [
38 : generate-rsa-keypair ( numbits -- <rsa> )
40 public-key over mod-inv +
43 : rsa-encrypt ( message rsa -- encrypted )
44 [ public-key>> ] [ modulus>> ] bi ^mod ;
46 : rsa-decrypt ( encrypted rsa -- message )
47 [ private-key>> ] [ modulus>> ] bi ^mod ;