{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_integer_gmp
#define MIN_VERSION_integer_gmp(a,b,c) 0
#endif
module Crypto.Number.ModArithmetic
(
expSafe
, expFast
, exponentiation_rtl_binary
, exponentiation
, exponantiation_rtl_binary
, exponantiation
, inverse
, inverseCoprimes
) where
import Control.Exception (throw, Exception)
import Data.Typeable
#if MIN_VERSION_integer_gmp(0,5,1)
import GHC.Integer.GMP.Internals
#else
import Crypto.Number.Basic (gcde_binary)
import Data.Bits
#endif
data CoprimesAssertionError = CoprimesAssertionError
deriving (Show,Typeable)
instance Exception CoprimesAssertionError
expSafe :: Integer
-> Integer
-> Integer
-> Integer
#if MIN_VERSION_integer_gmp(0,5,1)
expSafe b e m
| odd m = powModSecInteger b e m
| otherwise = powModInteger b e m
#else
expSafe = exponentiation
#endif
expFast :: Integer
-> Integer
-> Integer
-> Integer
expFast =
#if MIN_VERSION_integer_gmp(0,5,1)
powModInteger
#else
exponentiation
#endif
exponentiation_rtl_binary :: Integer -> Integer -> Integer -> Integer
#if MIN_VERSION_integer_gmp(0,5,1)
exponentiation_rtl_binary = expSafe
#else
exponentiation_rtl_binary 0 0 m = 1 `mod` m
exponentiation_rtl_binary b e m = loop e b 1
where sq x = (x * x) `mod` m
loop !0 _ !a = a `mod` m
loop !i !s !a = loop (i `shiftR` 1) (sq s) (if odd i then a * s else a)
#endif
exponentiation :: Integer -> Integer -> Integer -> Integer
#if MIN_VERSION_integer_gmp(0,5,1)
exponentiation = expSafe
#else
exponentiation b e m
| b == 1 = b
| e == 0 = 1
| e == 1 = b `mod` m
| even e = let p = (exponentiation b (e `div` 2) m) `mod` m
in (p^(2::Integer)) `mod` m
| otherwise = (b * exponentiation b (e-1) m) `mod` m
#endif
exponantiation_rtl_binary :: Integer -> Integer -> Integer -> Integer
exponantiation_rtl_binary = exponentiation_rtl_binary
exponantiation :: Integer -> Integer -> Integer -> Integer
exponantiation = exponentiation
inverse :: Integer -> Integer -> Maybe Integer
#if MIN_VERSION_integer_gmp(0,5,1)
inverse g m
| r == 0 = Nothing
| otherwise = Just r
where r = recipModInteger g m
#else
inverse g m
| d > 1 = Nothing
| otherwise = Just (x `mod` m)
where (x,_,d) = gcde_binary g m
#endif
inverseCoprimes :: Integer -> Integer -> Integer
inverseCoprimes g m =
case inverse g m of
Nothing -> throw CoprimesAssertionError
Just i -> i