# Crypto.Number.Basic: exported symbols usage examples

## Symbols

• areEven No usage example found for this symbol :( Collapse [-]
gcde See 5 Occurences [+] Collapse [-]
Found in Crypto.Number.ModArithmetic from the package cryptonite
```    | 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

-- | @inverse@ computes the modular inverse as in /g^(-1) mod m/.
inverse :: Integer -> Integer -> Maybe Integer
inverse g m = gmpInverse g m `onGmpUnsupported` v
where
v
| d > 1     = Nothing
| otherwise = Just (x `mod` m)
(x,_,d) = gcde g m

-- | Compute the modular inverse of two coprime numbers.
-- This is equivalent to inverse except that the result
-- is known to exists.
--
```

Found in Crypto.Number.Prime from the package cryptonite
```primalityTestNaive :: Integer -> Bool
primalityTestNaive n
| n <= 1    = False
| n == 2    = True
| even n    = False
| otherwise = search 3
where !ubound = snd \$ sqrti n
search !i
| i > ubound    = True
| i `divides` n = False
| otherwise     = search (i+2)

-- | Test is two integer are coprime to each other
isCoprime :: Integer -> Integer -> Bool
isCoprime m n = case gcde m n of (_,_,d) -> d == 1

-- | List of the first primes till 2903.
firstPrimes :: [Integer]
firstPrimes =
[ 2    , 3    , 5    , 7    , 11   , 13   , 17   , 19   , 23   , 29
```

Found in Crypto.Number.Prime from the package cryptonite
```    , generateSafePrime
, isProbablyPrime
, findPrimeFrom
, findPrimeFromWith
, primalityTestMillerRabin
, primalityTestNaive
, primalityTestFermat
, isCoprime
) where

import Crypto.Internal.Imports

import Crypto.Number.Compat
import Crypto.Number.Generate
import Crypto.Number.Basic (sqrti, gcde)
import Crypto.Number.ModArithmetic (expSafe)
import Crypto.Random.Types
import Crypto.Random.Probabilistic
import Crypto.Error
```

Found in Crypto.PubKey.ElGamal from the package cryptonite
```signWith :: (ByteArrayAccess msg, HashAlgorithm hash)
=> Integer         -- ^ random number k, between 0 and p-1 and gcd(k,p-1)=1
-> Params          -- ^ DH params (p,g)
-> PrivateNumber   -- ^ DH private key
-> hash            -- ^ collision resistant hash algorithm
-> msg             -- ^ message to sign
-> Maybe Signature
signWith k (Params p g _) (PrivateNumber x) hashAlg msg
| k >= p-1 || d > 1 = Nothing -- gcd(k,p-1) is not 1
| s == 0            = Nothing
| otherwise         = Just \$ Signature (r,s)
where r          = expSafe g k p
h          = os2ip \$ hashWith hashAlg msg
s          = ((h - x*r) * kInv) `mod` (p-1)
(kInv,_,d) = gcde k (p-1)

-- | sign message
--
-- This function will generate a random number, however
-- as the signature might fail, the function will automatically retry
```

Found in Crypto.PubKey.ElGamal from the package cryptonite
```    , decrypt
-- * Signature primitives
, signWith
, sign
-- * Verification primitives
, verify
) where

import Data.Maybe (fromJust)
import Crypto.Internal.Imports
import Crypto.Internal.ByteArray (ByteArrayAccess)
import Crypto.Number.ModArithmetic (expSafe, expFast, inverse)
import Crypto.Number.Generate (generateMax)
import Crypto.Number.Serialize (os2ip)
import Crypto.Number.Basic (gcde)
import Crypto.Random.Types
import Crypto.PubKey.DH (PrivateNumber(..), PublicNumber(..), Params(..), SharedKey(..))
import Crypto.Hash

-- | ElGamal Signature
```

log2 See 10 Occurences [+] Collapse [-]
Found in Crypto.Number.F2m from the package cryptonite
```{-# INLINE squareF2m' #-}

-- | Extended GCD algorithm for polynomials. For @a@ and @b@ returns @(g, u, v)@ such that @a * u + b * v == g@.
--
-- Reference: https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#B.C3.A9zout.27s_identity_and_extended_GCD_algorithm
gcdF2m :: Integer
-> Integer
-> (Integer, Integer, Integer)
gcdF2m a b = go (a, b, 1, 0, 0, 1)
where
go (g, 0, u, _, v, _)
= (g, u, v)
go (r0, r1, s0, s1, t0, t1)
= go (r1, r0 `addF2m` shift r1 j, s1, s0 `addF2m` shift s1 j, t1, t0 `addF2m` shift t1 j)
where j = max 0 (log2 r0 - log2 r1)

-- | Modular inversion over F₂m.
-- If @n@ doesn't have an inverse, 'Nothing' is returned.
--
-- This function is undefined for negative arguments, because their bit
```

Found in Crypto.Number.F2m from the package cryptonite
```{-# INLINE squareF2m' #-}

-- | Extended GCD algorithm for polynomials. For @a@ and @b@ returns @(g, u, v)@ such that @a * u + b * v == g@.
--
-- Reference: https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#B.C3.A9zout.27s_identity_and_extended_GCD_algorithm
gcdF2m :: Integer
-> Integer
-> (Integer, Integer, Integer)
gcdF2m a b = go (a, b, 1, 0, 0, 1)
where
go (g, 0, u, _, v, _)
= (g, u, v)
go (r0, r1, s0, s1, t0, t1)
= go (r1, r0 `addF2m` shift r1 j, s1, s0 `addF2m` shift s1 j, t1, t0 `addF2m` shift t1 j)
where j = max 0 (log2 r0 - log2 r1)

-- | Modular inversion over F₂m.
-- If @n@ doesn't have an inverse, 'Nothing' is returned.
--
-- This function is undefined for negative arguments, because their bit
```

Found in Crypto.Number.F2m from the package cryptonite
```squareF2m fx = modF2m fx . squareF2m'
{-# INLINE squareF2m #-}

-- | Squaring over F₂m without reduction by modulo.
--
-- The implementation utilizes the fact that for binary polynomial S(x) we have
-- S(x)^2 = S(x^2). In other words, insert a zero bit between every bits of argument: 1101 -> 1010001.
--
-- This function is undefined for negative arguments, because their bit
-- representation is platform-dependent.
squareF2m' :: Integer
-> Integer
squareF2m' n
| n < 0     = error "mulF2m: negative number represent no binary binary polynomial"
| otherwise = foldl' (\acc s -> if testBit n s then setBit acc (2 * s) else acc) 0 [0 .. log2 n]
{-# INLINE squareF2m' #-}

-- | Extended GCD algorithm for polynomials. For @a@ and @b@ returns @(g, u, v)@ such that @a * u + b * v == g@.
--
-- Reference: https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#B.C3.A9zout.27s_identity_and_extended_GCD_algorithm
```

Found in Crypto.Number.F2m from the package cryptonite
```-- | Multiplication over F₂m.
--
-- This function is undefined for negative arguments, because their bit
-- representation is platform-dependent. Zero modulus is also prohibited.
mulF2m :: BinaryPolynomial -- ^ Modulus
-> Integer
-> Integer
-> Integer
mulF2m fx n1 n2
|    fx < 0
|| n1 < 0
|| n2 < 0 = error "mulF2m: negative number represent no binary binary polynomial"
| fx == 0   = error "modF2m: cannot multiply modulo zero polynomial"
| otherwise = modF2m fx \$ go (if n2 `mod` 2 == 1 then n1 else 0) (log2 n2)
where
go n s | s == 0  = n
| otherwise = if testBit n2 s
then go (n `addF2m` shift n1 s) (s - 1)
else go n (s - 1)
```

Found in Crypto.Number.F2m from the package cryptonite
```-- representation is platform-dependent. Zero modulus is also prohibited.
modF2m :: BinaryPolynomial -- ^ Modulus
-> Integer
-> Integer
modF2m fx i
| fx < 0 || i < 0 = error "modF2m: negative number represent no binary polynomial"
| fx == 0         = error "modF2m: cannot divide by zero polynomial"
| fx == 1         = 0
| otherwise       = go i
where
lfx = log2 fx
go n | s == 0    = n `addF2m` fx
| s < 0     = n
| otherwise = go \$ n `addF2m` shift fx s
where s = log2 n - lfx
{-# INLINE modF2m #-}

-- | Multiplication over F₂m.
--
-- This function is undefined for negative arguments, because their bit
```

Found in Crypto.Number.F2m from the package cryptonite
```-- | Reduction by modulo over F₂m.
--
-- This function is undefined for negative arguments, because their bit
-- representation is platform-dependent. Zero modulus is also prohibited.
modF2m :: BinaryPolynomial -- ^ Modulus
-> Integer
-> Integer
modF2m fx i
| fx < 0 || i < 0 = error "modF2m: negative number represent no binary polynomial"
| fx == 0         = error "modF2m: cannot divide by zero polynomial"
| fx == 1         = 0
| otherwise       = go i
where
lfx = log2 fx
go n | s == 0    = n `addF2m` fx
| s < 0     = n
| otherwise = go \$ n `addF2m` shift fx s
where s = log2 n - lfx
{-# INLINE modF2m #-}
```

Found in Crypto.JOSE.Types from the package jose
```-- | A base64url encoded octet sequence interpreted as an integer
-- and where the number of octets carries explicit bit-length
-- information.
--
data SizedBase64Integer = SizedBase64Integer Int Integer
deriving (Show)

instance Eq SizedBase64Integer where
SizedBase64Integer _ n == SizedBase64Integer _ m = n == m

instance Arbitrary SizedBase64Integer where
arbitrary = do
x <- arbitraryBigInteger
l <- Test.QuickCheck.elements [0,1,2]  -- number of leading zero-bytes
pure \$ SizedBase64Integer ((log2 x `div` 8) + 1 + l) x

genByteStringOf :: Int -> Gen B.ByteString
genByteStringOf n = B.pack <\$> vectorOf n arbitrary

-- | Generate a 'SizedBase64Integer' of the given number of bytes
```

Found in Crypto.JOSE.Types from the package jose
```  , base64url
) where

import Data.Word (Word8)

import Control.Lens
import Data.Aeson
import Data.Aeson.Types (Parser)
import qualified Data.ByteString as B
import Data.X509
import Network.URI (URI)
import Test.QuickCheck
import Test.QuickCheck.Instances ()

import Crypto.Number.Basic (log2)
import Crypto.JOSE.Types.Internal
import Crypto.JOSE.Types.Orphans ()

-- | A base64url encoded octet sequence interpreted as an integer.
```

Found in Crypto.JOSE.Types.Internal from the package jose
```-- | Convert an integer to its unsigned big endian representation as
-- an octet sequence.
--
integerToBS :: Integral a => a -> B.ByteString
integerToBS = B.reverse . B.unfoldr (fmap swap . f)
where
f 0 = Nothing
f x = Just (fromIntegral <\$> quotRem x 256)

sizedIntegerToBS :: Integral a => Int -> a -> B.ByteString
sizedIntegerToBS w = zeroPad . integerToBS
where zeroPad xs = B.replicate (w - B.length xs) 0 `B.append` xs

intBytes :: Integer -> Int
intBytes n = (log2 n `div` 8) + 1
```

Found in Crypto.JOSE.Types.Internal from the package jose
```  , integerToBS
, intBytes
, sizedIntegerToBS
, base64url
) where

import Data.Bifunctor (first)
import Data.Char (ord)
import Data.Monoid ((<>))
import Data.Tuple (swap)
import Data.Word (Word8)

import Control.Lens
import Control.Lens.Cons.Extras
import Crypto.Number.Basic (log2)
import Data.Aeson.Types
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base64.URL as B64U
```

numBits See 15 Occurences [+] Collapse [-]
Found in Crypto.Number.Generate from the package cryptonite
```        loopGenerateOver count
| count == 0 = error \$ "internal: generateMax(" ++ show range ++ " bits=" ++ show bits ++ ") (over) doesn't seems to work properly"
| otherwise  = do
r <- generateParams (bits+1) Nothing False
let r2 = r - range
r3 = r2 - range
if isValid r
then return r
else if isValid r2
then return r2
else if isValid r3
then return r3
else loopGenerateOver (count-1)

bits            = numBits range
canOverGenerate = bits > 3 && not (range `testBit` (bits-2)) && not (range `testBit` (bits-3))

isValid n = n < range

tries :: Int
```

Found in Crypto.PubKey.DSA from the package cryptonite
```verify :: (ByteArrayAccess msg, HashAlgorithm hash) => hash -> PublicKey -> Signature -> msg -> Bool
verify hashAlg pk (Signature r s) m
-- Reject the signature if either 0 < r < q or 0 < s < q is not satisfied.
| r <= 0 || r >= q || s <= 0 || s >= q = False
| otherwise                            = v == r
where (Params p g q) = public_params pk
y       = public_y pk
hm      = os2ip . truncateHash \$ hashWith hashAlg m

w       = fromJust \$ inverse s q
u1      = (hm*w) `mod` q
u2      = (r*w) `mod` q
v       = ((expFast g u1 p) * (expFast y u2 p)) `mod` p `mod` q
-- if the hash is larger than the size of q, truncate it; FIXME: deal with the case of a q not evenly divisible by 8
truncateHash h = if numBits (os2ip h) > numBits q then takeView h (numBits q `div` 8) else dropView h 0
```

Found in Crypto.PubKey.DSA from the package cryptonite
```verify :: (ByteArrayAccess msg, HashAlgorithm hash) => hash -> PublicKey -> Signature -> msg -> Bool
verify hashAlg pk (Signature r s) m
-- Reject the signature if either 0 < r < q or 0 < s < q is not satisfied.
| r <= 0 || r >= q || s <= 0 || s >= q = False
| otherwise                            = v == r
where (Params p g q) = public_params pk
y       = public_y pk
hm      = os2ip . truncateHash \$ hashWith hashAlg m

w       = fromJust \$ inverse s q
u1      = (hm*w) `mod` q
u2      = (r*w) `mod` q
v       = ((expFast g u1 p) * (expFast y u2 p)) `mod` p `mod` q
-- if the hash is larger than the size of q, truncate it; FIXME: deal with the case of a q not evenly divisible by 8
truncateHash h = if numBits (os2ip h) > numBits q then takeView h (numBits q `div` 8) else dropView h 0
```

Found in Crypto.PubKey.DSA from the package cryptonite
```verify :: (ByteArrayAccess msg, HashAlgorithm hash) => hash -> PublicKey -> Signature -> msg -> Bool
verify hashAlg pk (Signature r s) m
-- Reject the signature if either 0 < r < q or 0 < s < q is not satisfied.
| r <= 0 || r >= q || s <= 0 || s >= q = False
| otherwise                            = v == r
where (Params p g q) = public_params pk
y       = public_y pk
hm      = os2ip . truncateHash \$ hashWith hashAlg m

w       = fromJust \$ inverse s q
u1      = (hm*w) `mod` q
u2      = (r*w) `mod` q
v       = ((expFast g u1 p) * (expFast y u2 p)) `mod` p `mod` q
-- if the hash is larger than the size of q, truncate it; FIXME: deal with the case of a q not evenly divisible by 8
truncateHash h = if numBits (os2ip h) > numBits q then takeView h (numBits q `div` 8) else dropView h 0
```

Found in Crypto.PubKey.DSA from the package cryptonite
```    , sign
, signWith
-- * Verification primitive
, verify
-- * Key pair
, KeyPair(..)
, toPublicKey
, toPrivateKey
) where

import           Crypto.Random.Types
import           Data.Bits (testBit)
import           Data.Data
import           Data.Maybe
import           Crypto.Number.Basic (numBits)
import           Crypto.Number.ModArithmetic (expFast, expSafe, inverse)
import           Crypto.Number.Serialize
import           Crypto.Number.Generate
import           Crypto.Internal.ByteArray (ByteArrayAccess(length), convert, index, dropView, takeView)
import           Crypto.Internal.Imports
```

Found in Crypto.PubKey.ECC.ECDSA from the package cryptonite
```            x  = pointAddTwoMuls curve u1 g u2 q
case x of
PointO     -> Nothing
Point x1 _ -> return \$ x1 `mod` n
where n = ecc_n cc
g = ecc_g cc
cc = common_curve \$ public_curve pk

-- | Truncate and hash.
tHash :: (ByteArrayAccess msg, HashAlgorithm hash) => hash -> msg -> Integer -> Integer
tHash hashAlg m n
| d > 0 = shiftR e d
| otherwise = e
where e = os2ip \$ hashWith hashAlg m
d = hashDigestSize hashAlg * 8 - numBits n
```

Found in Crypto.PubKey.ECC.ECDSA from the package cryptonite
```    , PrivateKey(..)
, KeyPair(..)
, toPublicKey
, toPrivateKey
, signWith
, sign
, verify
) where

import Control.Monad
import Crypto.Random.Types
import Data.Bits (shiftR)
import Crypto.Internal.ByteArray (ByteArrayAccess)
import Data.Data
import Crypto.Number.Basic (numBits)
import Crypto.Number.ModArithmetic (inverse)
import Crypto.Number.Serialize
import Crypto.Number.Generate
import Crypto.PubKey.ECC.Types
import Crypto.PubKey.ECC.Prim
```

Found in Crypto.PubKey.ECC.Types from the package cryptonite
```    , (SEC_t233r1, [1,3,132,0,27])
, (SEC_t239k1, [1,3,132,0,3])
, (SEC_t283k1, [1,3,132,0,16])
, (SEC_t283r1, [1,3,132,0,17])
, (SEC_t409k1, [1,3,132,0,36])
, (SEC_t409r1, [1,3,132,0,37])
, (SEC_t571k1, [1,3,132,0,38])
, (SEC_t571r1, [1,3,132,0,39])
]
-}

-- | get the size of the curve in bits
curveSizeBits :: Curve -> Int
curveSizeBits (CurveFP  c) = numBits (ecc_p  c)
curveSizeBits (CurveF2m c) = numBits (ecc_fx c) - 1

-- | Get the curve definition associated with a recommended known curve name.
getCurveByName :: CurveName -> Curve
getCurveByName SEC_p112r1 = CurveFP  \$ CurvePrime
0xdb7c2abf62e35e668076bead208b
```

Found in Crypto.PubKey.ECC.Types from the package cryptonite
```    , (SEC_t233k1, [1,3,132,0,26])
, (SEC_t233r1, [1,3,132,0,27])
, (SEC_t239k1, [1,3,132,0,3])
, (SEC_t283k1, [1,3,132,0,16])
, (SEC_t283r1, [1,3,132,0,17])
, (SEC_t409k1, [1,3,132,0,36])
, (SEC_t409r1, [1,3,132,0,37])
, (SEC_t571k1, [1,3,132,0,38])
, (SEC_t571r1, [1,3,132,0,39])
]
-}

-- | get the size of the curve in bits
curveSizeBits :: Curve -> Int
curveSizeBits (CurveFP  c) = numBits (ecc_p  c)
curveSizeBits (CurveF2m c) = numBits (ecc_fx c) - 1

-- | Get the curve definition associated with a recommended known curve name.
getCurveByName :: CurveName -> Curve
getCurveByName SEC_p112r1 = CurveFP  \$ CurvePrime
```

Found in Crypto.PubKey.ECC.Types from the package cryptonite
```    , CurveBinary(..)
, CurvePrime(..)
, common_curve
, curveSizeBits
, ecc_fx
, ecc_p
, CurveCommon(..)
-- * Recommended curves definition
, CurveName(..)
, getCurveByName
) where

import           Data.Data
import           Crypto.Internal.Imports
import           Crypto.Number.Basic (numBits)

-- | Define either a binary curve or a prime curve.
data Curve = CurveF2m CurveBinary -- ^ 𝔽(2^m)
| CurveFP  CurvePrime  -- ^ 𝔽p
deriving (Show,Read,Eq,Data,Typeable)
```

Found in Crypto.ECC.Simple.Types from the package cryptonite
```import           Data.Data
import           Crypto.Internal.Imports
import           Crypto.Number.Basic (numBits)

class Curve curve where
curveParameters :: proxy curve -> CurveParameters curve
curveType :: proxy curve -> CurveType

-- | get the size of the curve in bits
curveSizeBits :: Curve curve => proxy curve -> Int
curveSizeBits proxy =
case curveType proxy of
CurvePrime (CurvePrimeParam p)   -> numBits p
CurveBinary (CurveBinaryParam c) -> numBits c - 1

-- | get the size of the curve in bytes
curveSizeBytes :: Curve curve => proxy curve -> Int
curveSizeBytes proxy = (curveSizeBits proxy + 7) `div` 8
```

Found in Crypto.ECC.Simple.Types from the package cryptonite
```    ) where

import           Data.Data
import           Crypto.Internal.Imports
import           Crypto.Number.Basic (numBits)

class Curve curve where
curveParameters :: proxy curve -> CurveParameters curve
curveType :: proxy curve -> CurveType

-- | get the size of the curve in bits
curveSizeBits :: Curve curve => proxy curve -> Int
curveSizeBits proxy =
case curveType proxy of
CurvePrime (CurvePrimeParam p)   -> numBits p
CurveBinary (CurveBinaryParam c) -> numBits c - 1

-- | get the size of the curve in bytes
curveSizeBytes :: Curve curve => proxy curve -> Int
curveSizeBytes proxy = (curveSizeBits proxy + 7) `div` 8
```

Found in Crypto.ECC.Simple.Types from the package cryptonite
```    , SEC_t193r2(..)
, SEC_t233k1(..) -- aka NIST K-233
, SEC_t233r1(..)
, SEC_t239k1(..)
, SEC_t283k1(..)
, SEC_t283r1(..)
, SEC_t409k1(..)
, SEC_t409r1(..)
, SEC_t571k1(..)
, SEC_t571r1(..)
) where

import           Data.Data
import           Crypto.Internal.Imports
import           Crypto.Number.Basic (numBits)

class Curve curve where
curveParameters :: proxy curve -> CurveParameters curve
curveType :: proxy curve -> CurveType
```

Found in Network.TLS.Crypto.DH from the package tls
```import           Network.TLS.RNG

type DHPublic   = DH.PublicNumber
type DHPrivate  = DH.PrivateNumber
type DHParams   = DH.Params
type DHKey      = DH.SharedKey

dhPublic :: Integer -> DHPublic
dhPublic = DH.PublicNumber

dhPrivate :: Integer -> DHPrivate
dhPrivate = DH.PrivateNumber

dhParams :: Integer -> Integer -> DHParams
dhParams p g = DH.Params p g (numBits p)

dhGenerateKeyPair :: MonadRandom r => DHParams -> r (DHPrivate, DHPublic)
dhGenerateKeyPair params = do
priv <- DH.generatePrivate params
let pub        = DH.calculatePublic params priv
```

Found in Network.TLS.Crypto.DH from the package tls
```    -- * DH methods
, dhPublic
, dhPrivate
, dhParams
, dhParamsGetP
, dhParamsGetG
, dhGenerateKeyPair
, dhGetShared
, dhValid
, dhUnwrap
, dhUnwrapPublic
) where

import qualified Crypto.PubKey.DH as DH
import           Crypto.Number.Basic (numBits)
import qualified Data.ByteArray as B
import           Network.TLS.RNG

type DHPublic   = DH.PublicNumber
type DHPrivate  = DH.PrivateNumber
```

numBytes See 6 Occurences [+] Collapse [-]
Found in Crypto.Number.Serialize from the package cryptonite
```i2osp m = B.allocAndFreeze sz (\p -> Internal.i2osp m p sz >> return ())
where
!sz = numBytes m

-- | Just like 'i2osp', but takes an extra parameter for size.
-- If the number is too big to fit in @len@ bytes, 'Nothing' is returned
-- otherwise the number is padded with 0 to fit the @len@ required.
i2ospOf :: B.ByteArray ba => Int -> Integer -> Maybe ba
i2ospOf len m
| len <= 0  = Nothing
| m < 0     = Nothing
| sz > len  = Nothing
| otherwise = Just \$ B.unsafeCreate len (\p -> Internal.i2ospOf m p len >> return ())
where
!sz = numBytes m

-- | Just like 'i2ospOf' except that it doesn't expect a failure: i.e.
-- an integer larger than the number of output bytes requested.
--
-- For example if you just took a modulo of the number that represent
```

Found in Crypto.Number.Serialize from the package cryptonite
```import qualified Crypto.Internal.ByteArray as B
import qualified Crypto.Number.Serialize.Internal as Internal

-- | @os2ip@ converts a byte string into a positive integer.
os2ip :: B.ByteArrayAccess ba => ba -> Integer
os2ip bs = unsafeDoIO \$ B.withByteArray bs (\p -> Internal.os2ip p (B.length bs))

-- | @i2osp@ converts a positive integer into a byte string.
--
-- The first byte is MSB (most significant byte); the last byte is the LSB (least significant byte)
i2osp :: B.ByteArray ba => Integer -> ba
i2osp 0 = B.allocAndFreeze 1  (\p -> Internal.i2osp 0 p 1 >> return ())
i2osp m = B.allocAndFreeze sz (\p -> Internal.i2osp m p sz >> return ())
where
!sz = numBytes m

-- | Just like 'i2osp', but takes an extra parameter for size.
-- If the number is too big to fit in @len@ bytes, 'Nothing' is returned
-- otherwise the number is padded with 0 to fit the @len@ required.
i2ospOf :: B.ByteArray ba => Int -> Integer -> Maybe ba
```

Found in Crypto.Number.Serialize.Internal from the package cryptonite
```  where
!sz    = numBytes m

-- | Similar to 'i2osp', except it will pad any remaining space with zero.
i2ospOf :: Integer -> Ptr Word8 -> Int -> IO Int
i2ospOf m ptr ptrSz
| ptrSz <= 0 = return 0
| m < 0      = return 0
| ptrSz < sz = return 0
| otherwise  = do
memSet ptr 0 ptrSz
fillPtr (ptr `plusPtr` padSz) sz m
return ptrSz
where
!sz    = numBytes m
!padSz = ptrSz - sz

fillPtr :: Ptr Word8 -> Int -> Integer -> IO ()
fillPtr p sz m = gmpExportInteger m p `onGmpUnsupported` export (sz-1) m
where
```

Found in Crypto.Number.Serialize.Internal from the package cryptonite
```-- | Fill a pointer with the big endian binary representation of an integer
--
-- If the room available @ptrSz is less than the number of bytes needed,
-- 0 is returned. Likewise if a parameter is invalid, 0 is returned.
--
-- Returns the number of bytes written
i2osp :: Integer -> Ptr Word8 -> Int -> IO Int
i2osp m ptr ptrSz
| ptrSz <= 0 = return 0
| m < 0      = return 0
| m == 0     = pokeByteOff ptr 0 (0 :: Word8) >> return 1
| ptrSz < sz = return 0
| otherwise  = fillPtr ptr sz m >> return sz
where
!sz    = numBytes m

-- | Similar to 'i2osp', except it will pad any remaining space with zero.
i2ospOf :: Integer -> Ptr Word8 -> Int -> IO Int
i2ospOf m ptr ptrSz
| ptrSz <= 0 = return 0
```

Found in Network.TLS.Util.Serialization from the package tls
```module Network.TLS.Util.Serialization
( os2ip
, i2osp
, i2ospOf_
, lengthBytes
) where

import Crypto.Number.Basic      (numBytes)
import Crypto.Number.Serialize (os2ip, i2osp, i2ospOf_)

lengthBytes :: Integer -> Int
lengthBytes = numBytes
```

Found in Network.TLS.Util.Serialization from the package tls
```module Network.TLS.Util.Serialization
( os2ip
, i2osp
, i2ospOf_
, lengthBytes
) where

import Crypto.Number.Basic      (numBytes)
import Crypto.Number.Serialize (os2ip, i2osp, i2ospOf_)

lengthBytes :: Integer -> Int
lengthBytes = numBytes
```

sqrti See 2 Occurences [+] Collapse [-]
Found in Crypto.Number.Prime from the package cryptonite
```                    -> Integer -- ^ number to test for primality
-> Bool
primalityTestFermat n a p = and \$ map expTest [a..(a+fromIntegral n)]
where !pm1 = p-1
expTest i = expSafe i pm1 p == 1

-- | Test naively is integer is prime.
-- while naive, we skip even number and stop iteration at i > sqrt(n)
primalityTestNaive :: Integer -> Bool
primalityTestNaive n
| n <= 1    = False
| n == 2    = True
| even n    = False
| otherwise = search 3
where !ubound = snd \$ sqrti n
search !i
| i > ubound    = True
| i `divides` n = False
| otherwise     = search (i+2)
```

Found in Crypto.Number.Prime from the package cryptonite
```    , generateSafePrime
, isProbablyPrime
, findPrimeFrom
, findPrimeFromWith
, primalityTestMillerRabin
, primalityTestNaive
, primalityTestFermat
, isCoprime
) where

import Crypto.Internal.Imports

import Crypto.Number.Compat
import Crypto.Number.Generate
import Crypto.Number.Basic (sqrti, gcde)
import Crypto.Number.ModArithmetic (expSafe)
import Crypto.Random.Types
import Crypto.Random.Probabilistic
import Crypto.Error
```