From 19b7ab375a80a0690deb7b149dcb4a602ea6ecfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Ch=C3=A9ron?= Date: Sun, 8 Oct 2017 09:21:45 +0200 Subject: [PATCH] Time-constant modular inverse --- Crypto/Number/ModArithmetic.hs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Crypto/Number/ModArithmetic.hs b/Crypto/Number/ModArithmetic.hs index dcd8663..3d46aaa 100644 --- a/Crypto/Number/ModArithmetic.hs +++ b/Crypto/Number/ModArithmetic.hs @@ -16,6 +16,7 @@ module Crypto.Number.ModArithmetic , inverse , inverseCoprimes , jacobi + , inverseFermat ) where import Control.Exception (throw, Exception) @@ -120,3 +121,8 @@ jacobi a n n1 = n `mod` a1 in if a1 == 1 then Just s else fmap (*s) (jacobi n1 a1) + +-- | Modular inverse using Fermat's little theorem. This works only when +-- the modulus is prime but avoids side channels like in 'expSafe'. +inverseFermat :: Integer -> Integer -> Integer +inverseFermat g p = expSafe g (p - 2) p