File: Types.hs

package info (click to toggle)
haskell-crypton 1.0.4-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,548 kB
  • sloc: haskell: 26,764; ansic: 22,294; makefile: 6
file content (52 lines) | stat: -rw-r--r-- 1,519 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
-- |
-- Module      : Crypto.PubKey.Rabin.Types
-- License     : BSD-style
-- Maintainer  : Carlos Rodriguez-Vega <crodveg@yahoo.es>
-- Stability   : experimental
-- Portability : unknown
module Crypto.PubKey.Rabin.Types (
    Error (..),
    generatePrimes,
) where

import Crypto.Number.Basic (numBits)
import Crypto.Number.Prime (findPrimeFromWith, generatePrime)
import Crypto.Random.Types

type PrimeCondition = Integer -> Bool

-- | Error possible during encryption, decryption or signing.
data Error
    = -- | the message to encrypt is too long
      MessageTooLong
    | -- | the message decrypted doesn't have a OAEP structure
      MessageNotRecognized
    | -- | some parameters lead to breaking assumptions
      InvalidParameters
    deriving (Show, Eq)

-- | Generate primes p & q
generatePrimes
    :: MonadRandom m
    => Int
    -- ^ size in bytes
    -> PrimeCondition
    -- ^ condition prime p must satisfy
    -> PrimeCondition
    -- ^ condition prime q must satisfy
    -> m (Integer, Integer)
    -- ^ chosen distinct primes p and q
generatePrimes size pCond qCond =
    let pBits = (8 * (size `div` 2))
        qBits = (8 * (size - (size `div` 2)))
     in do
            p <- generatePrime' pBits pCond
            q <- generatePrime' qBits qCond
            return (p, q)
  where
    generatePrime' bits cond = do
        pr' <- generatePrime bits
        let pr = findPrimeFromWith cond pr'
        if numBits pr == bits
            then return pr
            else generatePrime' bits cond