2008-10-02 19:45:51 -04:00
|
|
|
! Copyright (C) 2008 Doug Coleman.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2009-05-10 17:33:43 -04:00
|
|
|
USING: math.primes kernel math math.functions namespaces
|
|
|
|
sequences accessors ;
|
2007-09-20 18:09:08 -04:00
|
|
|
IN: crypto.rsa
|
|
|
|
|
2007-10-07 00:01:26 -04:00
|
|
|
! The private key is the only secret.
|
2007-09-20 18:09:08 -04:00
|
|
|
|
2007-10-07 00:01:26 -04:00
|
|
|
! p,q are two random primes of numbits/2
|
|
|
|
! phi = (p-1)(q-1)
|
|
|
|
! modulus = p*q
|
|
|
|
! public = 65537
|
|
|
|
! private = public modinv phi
|
|
|
|
|
|
|
|
TUPLE: rsa modulus private-key public-key ;
|
2007-09-20 18:09:08 -04:00
|
|
|
|
|
|
|
C: <rsa> rsa
|
|
|
|
|
2007-10-07 00:01:26 -04:00
|
|
|
<PRIVATE
|
|
|
|
|
2009-02-22 20:08:45 -05:00
|
|
|
CONSTANT: public-key 65537
|
2007-10-07 00:01:26 -04:00
|
|
|
|
|
|
|
: rsa-primes ( numbits -- p q )
|
2009-05-10 19:20:19 -04:00
|
|
|
2/ 2 swap unique-primes first2 ;
|
2007-10-07 00:01:26 -04:00
|
|
|
|
|
|
|
: modulus-phi ( numbits -- n phi )
|
|
|
|
#! Loop until phi is not divisible by the public key.
|
|
|
|
dup rsa-primes [ * ] 2keep
|
2009-08-13 20:21:44 -04:00
|
|
|
[ 1 - ] bi@ *
|
2011-10-17 23:36:28 -04:00
|
|
|
dup public-key gcd* 1 = [
|
2007-10-07 00:01:26 -04:00
|
|
|
rot drop
|
|
|
|
] [
|
|
|
|
2drop modulus-phi
|
|
|
|
] if ;
|
|
|
|
|
|
|
|
PRIVATE>
|
|
|
|
|
2007-09-20 18:09:08 -04:00
|
|
|
: generate-rsa-keypair ( numbits -- <rsa> )
|
2007-10-07 00:01:26 -04:00
|
|
|
modulus-phi
|
|
|
|
public-key over mod-inv +
|
|
|
|
public-key <rsa> ;
|
2007-09-20 18:09:08 -04:00
|
|
|
|
2007-10-07 00:01:26 -04:00
|
|
|
: rsa-encrypt ( message rsa -- encrypted )
|
2008-04-03 14:57:33 -04:00
|
|
|
[ public-key>> ] [ modulus>> ] bi ^mod ;
|
2007-09-20 18:09:08 -04:00
|
|
|
|
2007-10-07 00:01:26 -04:00
|
|
|
: rsa-decrypt ( encrypted rsa -- message )
|
2008-04-03 14:57:33 -04:00
|
|
|
[ private-key>> ] [ modulus>> ] bi ^mod ;
|