factor/extra/crypto/rsa/rsa.factor

48 lines
1.0 KiB
Factor
Raw Normal View History

2008-10-02 19:45:51 -04:00
! Copyright (C) 2008 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
2007-09-20 18:09:08 -04:00
USING: math.miller-rabin kernel math math.functions namespaces
2008-04-03 14:57:33 -04:00
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 )
2/ 2 unique-primes first2 ;
: modulus-phi ( numbits -- n phi )
#! Loop until phi is not divisible by the public key.
dup rsa-primes [ * ] 2keep
2008-03-29 21:36:58 -04:00
[ 1- ] bi@ *
2007-10-07 00:01:26 -04:00
dup public-key gcd nip 1 = [
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 ;