Use QuickCheck by generating primes
Asked Answered
T

2

13

Background

For fun, I'm trying to write a property for quick-check that can test the basic idea behind cryptography with RSA.

  • Choose two distinct primes, p and q.
  • Let N = p*q
  • e is some number relatively prime to (p-1)(q-1) (in practice, e is usually 3 for fast encoding)
  • d is the modular inverse of e modulo (p-1)(q-1)

For all x such that 1 < x < N, it is always true that (x^e)^d = x modulo N

In other words, x is the "message", raising it to the eth power mod N is the act of "encoding" the message, and raising the encoded message to the dth power mod N is the act of "decoding" it.

(The property is also trivially true for x = 1, a case which is its own encryption)

Code

Here are the methods I have coded up so far:

import Test.QuickCheck

-- modular exponentiation
modExp :: Integral a => a -> a -> a -> a
modExp y z n = modExp' (y `mod` n) z `mod` n
    where modExp' y z | z == 0 = 1
                      | even z =  modExp (y*y) (z `div` 2) n
                      | odd z  = (modExp (y*y) (z `div` 2) n) * y

-- relatively prime
rPrime :: Integral a => a -> a -> Bool
rPrime a b = gcd a b == 1

-- multiplicative inverse (modular)
mInverse :: Integral a => a -> a -> a
mInverse 1 _ = 1
mInverse x y = (n * y + 1) `div` x
    where n = x - mInverse (y `mod` x) x

-- just a quick way to test for primality
n `divides` x = x `mod` n == 0
primes = 2:filter isPrime [3..]
isPrime x = null . filter (`divides` x) $ takeWhile (\y -> y*y <= x) primes

-- the property
prop_rsa (p,q,x) = isPrime p  &&
                   isPrime q  &&
                   p /= q     &&
                   x > 1      &&
                   x < n      &&
                   rPrime e t ==>
                   x == (x `powModN` e) `powModN` d
    where e = 3
          n = p*q
          t = (p-1)*(q-1)
          d = mInverse e t
          a `powModN` b = modExp a b n

(Thanks, google and random blog, for the implementation of modular multiplicative inverse)

Question

The problem should be obvious: there are way too many conditions on the property to make it at all usable. Trying to invoke quickCheck prop_rsa in ghci made my terminal hang.

So I've poked around the QuickCheck manual a bit, and it says:

Properties may take the form

forAll <generator> $ \<pattern> -> <property>

How do I make a <generator> for prime numbers? Or with the other constraints, so that quickCheck doesn't have to sift through a bunch of failed conditions?

Any other general advice (especially regarding QuickCheck) is welcome.

Timekeeper answered 20/2, 2011 at 4:49 Comment(5)
Fun fact: QuickCheck helped me see that q and p must be distinct. Before I had that requirement, it was able to find examples that failed the prop when q == pTimekeeper
Props man, this is a beautifully asked question. Few people put this much effort into communicating what they want to know. Upvote.Epigone
You could use the Rabin-Miller probabilistic test; mathworld.wolfram.com/Rabin-MillerStrongPseudoprimeTest.htmlOutoftheway
Just found an implementation of the Rabin-Miller test here: bonsaicode.wordpress.com/2009/05/01/…Outoftheway
@Paul very nice! I've been working on tweaking the test so that it only uses small primes, mainly because testing larger numbers for primality was getting cumbersome. I'll take a look at working that into my code instead.Timekeeper
T
4

OK so here's what I did.

Top of file

{-# LANGUAGE NoMonomorphismRestriction #-}

import Test.QuickCheck
import Control.Applicative

All code as given in the question, except for prop_rsa. That was (obviously) heavily modified:

prop_rsa = forAll primePair $ \(p,q) ->
           let n = p*q
           in forAll (genUnder n) $ \x  ->
              let e = 3
                  t = (p-1)*(q-1)
                  d = mInverse e t
                  a `powModN` b = modExp a b n
              in p /= q &&
                 rPrime e t ==>
                 x == (x `powModN` e) `powModN` d

The type for primePair is Gen (Int, Int), and the type for genUnder is Int -> Gen Int. I'm not exactly sure what the magic is behind forAll but I'm pretty sure this is correct. I've done some ad-hoc adjustments to 1) make sure it fails if I mess up the conditions and 2) make sure the nested forAll is varying the value of x across test cases.

So here's how to write those generators. Once I realized that <generator> in the documentation just meant something of type Gen a, it was cake.

genNonzero = (\x -> if x == 0 then 1 else x) `fmap` arbitrary
genUnder :: Int -> Gen Int
genUnder n = ((`mod` n) . abs) `fmap` genNonzero

genSmallPrime = ((\x -> (primes !! (x `mod` 2500))) . abs) `fmap` arbitrary

primePair :: Gen (Int, Int)
primePair = (,) <$> genSmallPrime <*> genSmallPrime

primePair took some trial and error for me to get right; I knew that some combinators like that should work, but I'm still not as familiar with fmap, <$> and <*> as I'd like to be. I restricted the computation to only select from among the first 2500 primes; otherwise it apparently wanted to pick some really big ones that took forever to generate.

Random thing to note

Thanks to laziness, d = mInverse e t isn't computed unless the conditions are met. Which is good, because it's undefined when the condition rPrime e t is false. In English, an integer a only has a multiplicative inverse (mod b) when a and b are relatively prime.

Timekeeper answered 22/2, 2011 at 19:34 Comment(0)
R
4

Here's one way to make a QuickCheck-compatible prime-number generator (stealing a Sieve of Eratosthenes implementation from http://en.literateprograms.org/Sieve_of_Eratosthenes_(Haskell)):

import Test.QuickCheck

newtype Prime = Prime Int deriving Show

primes = sieve [2..]
    where
      sieve (p:xs) = Prime p : sieve [x | x <- xs, x `mod` p > 0]

instance Arbitrary Prime where
    arbitrary = do i <- arbitrary
                   return $ primes!!(abs i)

It can be used in QuickCheck like so:

prop_primes_dont_divide (Prime x) (Prime y) = x == y || x `mod` y > 0

For your use, you'd replace p and q with (Prime p) and (Prime q) in your property.

Ribbentrop answered 20/2, 2011 at 6:30 Comment(3)
You might want to use library code for the primes, it should be faster by a decent amount: hackage.haskell.org/package/primesStudbook
@Studbook probably better than what I or jacobm wrote, but the docs for isPrime currently say, "It is impractical for numbers with a very large smallest prime factor." Wikipedia has loads of interesting information on faster primality tests that I might try out.Timekeeper
this is a good answer; I tried it out and it was pretty good. But not quite what I was asking for. I'm particularly interested in using forAll here. Inspired by your answer I've actually come up with some stuff, but I want to wait and see if anyone else has something insightful to say before I post it.Timekeeper
T
4

OK so here's what I did.

Top of file

{-# LANGUAGE NoMonomorphismRestriction #-}

import Test.QuickCheck
import Control.Applicative

All code as given in the question, except for prop_rsa. That was (obviously) heavily modified:

prop_rsa = forAll primePair $ \(p,q) ->
           let n = p*q
           in forAll (genUnder n) $ \x  ->
              let e = 3
                  t = (p-1)*(q-1)
                  d = mInverse e t
                  a `powModN` b = modExp a b n
              in p /= q &&
                 rPrime e t ==>
                 x == (x `powModN` e) `powModN` d

The type for primePair is Gen (Int, Int), and the type for genUnder is Int -> Gen Int. I'm not exactly sure what the magic is behind forAll but I'm pretty sure this is correct. I've done some ad-hoc adjustments to 1) make sure it fails if I mess up the conditions and 2) make sure the nested forAll is varying the value of x across test cases.

So here's how to write those generators. Once I realized that <generator> in the documentation just meant something of type Gen a, it was cake.

genNonzero = (\x -> if x == 0 then 1 else x) `fmap` arbitrary
genUnder :: Int -> Gen Int
genUnder n = ((`mod` n) . abs) `fmap` genNonzero

genSmallPrime = ((\x -> (primes !! (x `mod` 2500))) . abs) `fmap` arbitrary

primePair :: Gen (Int, Int)
primePair = (,) <$> genSmallPrime <*> genSmallPrime

primePair took some trial and error for me to get right; I knew that some combinators like that should work, but I'm still not as familiar with fmap, <$> and <*> as I'd like to be. I restricted the computation to only select from among the first 2500 primes; otherwise it apparently wanted to pick some really big ones that took forever to generate.

Random thing to note

Thanks to laziness, d = mInverse e t isn't computed unless the conditions are met. Which is good, because it's undefined when the condition rPrime e t is false. In English, an integer a only has a multiplicative inverse (mod b) when a and b are relatively prime.

Timekeeper answered 22/2, 2011 at 19:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.