1 ! Copyright (C) 2008 Doug Coleman.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: math.primes 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 CONSTANT: public-key 65537
23 : rsa-primes ( numbits -- p q )
24 2/ 2 swap 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 coprime? [ nipd ] [ 2drop modulus-phi ] if ;
34 : generate-rsa-keypair ( numbits -- <rsa> )
36 public-key over mod-inv +
39 : rsa-encrypt ( message rsa -- encrypted )
40 [ public-key>> ] [ modulus>> ] bi ^mod ;
42 : rsa-decrypt ( encrypted rsa -- message )
43 [ private-key>> ] [ modulus>> ] bi ^mod ;