-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Cryptography Primitives sink -- -- A repository of cryptographic primitives. -- --
-- import Crypto.Hash -- -- sha1 :: ByteString -> Digest SHA1 -- sha1 = hash -- -- hexSha3_512 :: ByteString -> String -- hexSha3_512 bs = show (hash bs :: Digest SHA3_512) --module Crypto.Hash -- | Represent a context for a given hash algorithm. data Context a -- | Represent a digest for a given hash algorithm. -- -- This type is an instance of ByteArrayAccess from package -- memory. Module Data.ByteArray provides many primitives -- to work with those values including conversion to other types. -- -- Creating a digest from a bytearray is also possible with function -- digestFromByteString. data Digest a -- | Try to transform a bytearray into a Digest of specific algorithm. -- -- If the digest is not the right size for the algorithm specified, then -- Nothing is returned. digestFromByteString :: forall a ba. (HashAlgorithm a, ByteArrayAccess ba) => ba -> Maybe (Digest a) -- | Initialize a new context for a specified hash algorithm hashInitWith :: HashAlgorithm alg => alg -> Context alg -- | Run the hash function but takes an explicit hash algorithm -- parameter hashWith :: (ByteArrayAccess ba, HashAlgorithm alg) => alg -> ba -> Digest alg -- | Initialize a new context for this hash algorithm hashInit :: forall a. HashAlgorithm a => Context a -- | Update the context with a list of strict bytestring, and return a new -- context with the updates. hashUpdates :: forall a ba. (HashAlgorithm a, ByteArrayAccess ba) => Context a -> [ba] -> Context a -- | run hashUpdates on one single bytestring and return the updated -- context. hashUpdate :: (ByteArrayAccess ba, HashAlgorithm a) => Context a -> ba -> Context a -- | Finalize a context and return a digest. hashFinalize :: forall a. HashAlgorithm a => Context a -> Digest a -- | Get the block size of a hash algorithm hashBlockSize :: HashAlgorithm a => a -> Int -- | Get the digest size of a hash algorithm hashDigestSize :: HashAlgorithm a => a -> Int -- | Hash a strict bytestring into a digest. hash :: (ByteArrayAccess ba, HashAlgorithm a) => ba -> Digest a -- | Hash a lazy bytestring into a digest. hashlazy :: HashAlgorithm a => ByteString -> Digest a module Crypto.Cipher.CAST5 -- | CAST5 block cipher (also known as CAST-128). Key is between 40 and 128 -- bits. data CAST5 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.CAST5.CAST5 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.CAST5.CAST5 module Crypto.Cipher.Twofish data Twofish128 data Twofish192 data Twofish256 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Twofish.Twofish256 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Twofish.Twofish256 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Twofish.Twofish192 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Twofish.Twofish192 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Twofish.Twofish128 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Twofish.Twofish128 -- | Camellia support. only 128 bit variant available for now. module Crypto.Cipher.Camellia -- | Camellia block cipher with 128 bit key data Camellia128 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Camellia.Camellia128 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Camellia.Camellia128 module Crypto.Cipher.Blowfish -- | variable keyed blowfish state data Blowfish -- | 64 bit keyed blowfish state data Blowfish64 -- | 128 bit keyed blowfish state data Blowfish128 -- | 256 bit keyed blowfish state data Blowfish256 -- | 448 bit keyed blowfish state data Blowfish448 instance Control.DeepSeq.NFData Crypto.Cipher.Blowfish.Blowfish448 instance Control.DeepSeq.NFData Crypto.Cipher.Blowfish.Blowfish256 instance Control.DeepSeq.NFData Crypto.Cipher.Blowfish.Blowfish128 instance Control.DeepSeq.NFData Crypto.Cipher.Blowfish.Blowfish64 instance Control.DeepSeq.NFData Crypto.Cipher.Blowfish.Blowfish instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Blowfish.Blowfish448 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Blowfish.Blowfish448 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Blowfish.Blowfish256 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Blowfish.Blowfish256 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Blowfish.Blowfish128 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Blowfish.Blowfish128 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Blowfish.Blowfish64 instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Blowfish.Blowfish64 instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.Blowfish.Blowfish instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.Blowfish.Blowfish -- | Argon2 hashing function (P-H-C winner) -- -- Recommended to use this module qualified -- -- File started from Argon2.hs, from Oliver Charles at -- https://github.com/ocharles/argon2 module Crypto.KDF.Argon2 -- | Parameters that can be adjusted to change the runtime performance of -- the hashing. data Options Options :: !TimeCost -> !MemoryCost -> !Parallelism -> !Variant -> !Version -> Options [iterations] :: Options -> !TimeCost [memory] :: Options -> !MemoryCost [parallelism] :: Options -> !Parallelism -- | Which variant of Argon2 to use. [variant] :: Options -> !Variant -- | Which version of Argon2 to use. [version] :: Options -> !Version -- | The time cost, which defines the amount of computation realized and -- therefore the execution time, given in number of iterations. -- -- ARGON2_MIN_TIME <= hashIterations <= -- ARGON2_MAX_TIME type TimeCost = Word32 -- | The memory cost, which defines the memory usage, given in kibibytes. -- -- max ARGON2_MIN_MEMORY (8 * hashParallelism) <= -- hashMemory <= ARGON2_MAX_MEMORY type MemoryCost = Word32 -- | A parallelism degree, which defines the number of parallel threads. -- -- ARGON2_MIN_LANES <= hashParallelism <= -- ARGON2_MAX_LANES && ARGON_MIN_THREADS <= -- hashParallelism <= ARGON2_MAX_THREADS type Parallelism = Word32 -- | Which variant of Argon2 to use. You should choose the variant that is -- most applicable to your intention to hash inputs. data Variant -- | Argon2d is faster than Argon2i and uses data-depending memory access, -- which makes it suitable for cryptocurrencies and applications with no -- threats from side-channel timing attacks. Argon2d :: Variant -- | Argon2i uses data-independent memory access, which is preferred for -- password hashing and password-based key derivation. Argon2i is slower -- as it makes more passes over the memory to protect from tradeoff -- attacks. Argon2i :: Variant -- | Argon2id is a hybrid of Argon2i and Argon2d, using a combination of -- data-depending and data-independent memory accesses, which gives some -- of Argon2i's resistance to side-channel cache timing attacks and much -- of Argon2d's resistance to GPU cracking attacks Argon2id :: Variant -- | Which version of Argon2 to use data Version Version10 :: Version Version13 :: Version defaultOptions :: Options hash :: (ByteArrayAccess password, ByteArrayAccess salt, ByteArray out) => Options -> password -> salt -> Int -> CryptoFailable out instance GHC.Show.Show Crypto.KDF.Argon2.Options instance GHC.Read.Read Crypto.KDF.Argon2.Options instance GHC.Classes.Ord Crypto.KDF.Argon2.Options instance GHC.Classes.Eq Crypto.KDF.Argon2.Options instance GHC.Enum.Bounded Crypto.KDF.Argon2.Version instance GHC.Enum.Enum Crypto.KDF.Argon2.Version instance GHC.Show.Show Crypto.KDF.Argon2.Version instance GHC.Read.Read Crypto.KDF.Argon2.Version instance GHC.Classes.Ord Crypto.KDF.Argon2.Version instance GHC.Classes.Eq Crypto.KDF.Argon2.Version instance GHC.Enum.Bounded Crypto.KDF.Argon2.Variant instance GHC.Enum.Enum Crypto.KDF.Argon2.Variant instance GHC.Show.Show Crypto.KDF.Argon2.Variant instance GHC.Read.Read Crypto.KDF.Argon2.Variant instance GHC.Classes.Ord Crypto.KDF.Argon2.Variant instance GHC.Classes.Eq Crypto.KDF.Argon2.Variant -- | Provide the CMAC (Cipher based Message Authentification Code) base -- algorithm. http://en.wikipedia.org/wiki/CMAC -- http://csrc.nist.gov/publications/nistpubs/800-38B/SP_800-38B.pdf module Crypto.MAC.CMAC -- | compute a MAC using the supplied cipher cmac :: (ByteArrayAccess bin, BlockCipher cipher) => cipher -> bin -> CMAC cipher -- | Authentication code data CMAC a -- | make sub-keys used in CMAC subKeys :: (BlockCipher k, ByteArray ba) => k -> (ba, ba) instance Data.ByteArray.Types.ByteArrayAccess (Crypto.MAC.CMAC.CMAC a) instance GHC.Classes.Eq (Crypto.MAC.CMAC.CMAC a) -- | Provide the HMAC (Hash based Message Authentification Code) base -- algorithm. http://en.wikipedia.org/wiki/HMAC module Crypto.MAC.HMAC -- | compute a MAC using the supplied hashing function hmac :: (ByteArrayAccess key, ByteArrayAccess message, HashAlgorithm a) => key -> message -> HMAC a -- | Represent an HMAC that is a phantom type with the hash used to produce -- the mac. -- -- The Eq instance is constant time. newtype HMAC a HMAC :: Digest a -> HMAC a [hmacGetDigest] :: HMAC a -> Digest a -- | Represent an ongoing HMAC state, that can be appended with -- update and finalize to an HMAC with hmacFinalize data Context hashalg Context :: !(Context hashalg) -> !(Context hashalg) -> Context hashalg -- | Initialize a new incremental HMAC context initialize :: (ByteArrayAccess key, HashAlgorithm a) => key -> Context a -- | Incrementally update a HMAC context update :: (ByteArrayAccess message, HashAlgorithm a) => Context a -> message -> Context a -- | Increamentally update a HMAC context with multiple inputs updates :: (ByteArrayAccess message, HashAlgorithm a) => Context a -> [message] -> Context a -- | Finalize a HMAC context and return the HMAC. finalize :: HashAlgorithm a => Context a -> HMAC a instance Data.ByteArray.Types.ByteArrayAccess (Crypto.MAC.HMAC.HMAC a) instance GHC.Classes.Eq (Crypto.MAC.HMAC.HMAC a) -- | Password Based Key Derivation Function 2 module Crypto.KDF.PBKDF2 -- | The PRF used for PBKDF2 type PRF password = password the password parameters -> Bytes the content -> Bytes prf(password,content) -- | PRF for PBKDF2 using HMAC with the hash algorithm as parameter prfHMAC :: (HashAlgorithm a, ByteArrayAccess password) => a -> PRF password -- | Parameters for PBKDF2 data Parameters Parameters :: Int -> Int -> Parameters -- | the number of user-defined iterations for the algorithms. e.g. WPA2 -- uses 4000. [iterCounts] :: Parameters -> Int -- | the number of bytes to generate out of PBKDF2 [outputLength] :: Parameters -> Int -- | generate the pbkdf2 key derivation function from the output generate :: (ByteArrayAccess password, ByteArrayAccess salt, ByteArray ba) => PRF password -> Parameters -> password -> salt -> ba fastPBKDF2_SHA1 :: (ByteArrayAccess password, ByteArrayAccess salt, ByteArray out) => Parameters -> password -> salt -> out fastPBKDF2_SHA256 :: (ByteArrayAccess password, ByteArrayAccess salt, ByteArray out) => Parameters -> password -> salt -> out fastPBKDF2_SHA512 :: (ByteArrayAccess password, ByteArrayAccess salt, ByteArray out) => Parameters -> password -> salt -> out -- | Scrypt key derivation function as defined in Colin Percival's paper -- "Stronger Key Derivation via Sequential Memory-Hard Functions" -- http://www.tarsnap.com/scrypt/scrypt.pdf. module Crypto.KDF.Scrypt -- | Parameters for Scrypt data Parameters Parameters :: Word64 -> Int -> Int -> Int -> Parameters -- | Cpu/Memory cost ratio. must be a power of 2 greater than 1. also known -- as N. [n] :: Parameters -> Word64 -- | Must satisfy r * p < 2^30 [r] :: Parameters -> Int -- | Must satisfy r * p < 2^30 [p] :: Parameters -> Int -- | the number of bytes to generate out of Scrypt [outputLength] :: Parameters -> Int -- | Generate the scrypt key derivation data generate :: (ByteArrayAccess password, ByteArrayAccess salt, ByteArray output) => Parameters -> password -> salt -> output -- | Key Derivation Function based on HMAC -- -- See RFC5869 module Crypto.KDF.HKDF -- | Pseudo Random Key data PRK a -- | Extract a Pseudo Random Key using the parameter and the underlaying -- hash mechanism extract :: (HashAlgorithm a, ByteArrayAccess salt, ByteArrayAccess ikm) => salt -> ikm -> PRK a -- | Create a PRK directly from the input key material. -- -- Only use when guaranteed to have a good quality and random data to use -- directly as key. This effectively skip a HMAC with key=salt and -- data=key. extractSkip :: ByteArrayAccess ikm => ikm -> PRK a -- | Expand key material of specific length out of the parameters expand :: (HashAlgorithm a, ByteArrayAccess info, ByteArray out) => PRK a -> info -> Int -> out instance GHC.Classes.Eq (Crypto.KDF.HKDF.PRK a) instance Data.ByteArray.Types.ByteArrayAccess (Crypto.KDF.HKDF.PRK a) -- | Poly1305 implementation module Crypto.MAC.Poly1305 -- | Poly1305 State. use State instead of Ctx -- | Deprecated: use Poly1305 State instead type Ctx = State -- | Poly1305 State data State -- | Poly1305 Auth newtype Auth Auth :: Bytes -> Auth authTag :: ByteArrayAccess b => b -> CryptoFailable Auth -- | initialize a Poly1305 context initialize :: ByteArrayAccess key => key -> CryptoFailable State -- | update a context with a bytestring update :: ByteArrayAccess ba => State -> ba -> State -- | updates a context with multiples bytestring updates :: ByteArrayAccess ba => State -> [ba] -> State -- | finalize the context into a digest bytestring finalize :: State -> Auth -- | One-pass authorization creation auth :: (ByteArrayAccess key, ByteArrayAccess ba) => key -> ba -> Auth instance Control.DeepSeq.NFData Crypto.MAC.Poly1305.Auth instance Data.ByteArray.Types.ByteArrayAccess Crypto.MAC.Poly1305.Auth instance Data.ByteArray.Types.ByteArrayAccess Crypto.MAC.Poly1305.State instance GHC.Classes.Eq Crypto.MAC.Poly1305.Auth -- | A simple AEAD scheme using ChaCha20 and Poly1305. See RFC 7539. -- -- The State is not modified in place, so each function changing the -- State, returns a new State. -- -- Authenticated Data need to be added before any call to encrypt -- or decrypt, and once all the data has been added, then -- finalizeAAD need to be called. -- -- Once finalizeAAD has been called, no further appendAAD -- call should be make. -- --
-- import Data.ByteString.Char8 as B -- import Data.ByteArray -- import Crypto.Error -- import Crypto.Cipher.ChaChaPoly1305 as C -- -- encrypt -- :: ByteString -- nonce (12 random bytes) -- -> ByteString -- symmetric key -- -> ByteString -- optional associated data (won't be encrypted) -- -> ByteString -- input plaintext to be encrypted -- -> CryptoFailable ByteString -- ciphertext with a 128-bit tag attached -- encrypt nonce key header plaintext = do -- st1 <- C.nonce12 nonce >>= C.initialize key -- let -- st2 = C.finalizeAAD $ C.appendAAD header st1 -- (out, st3) = C.encrypt plaintext st2 -- auth = C.finalize st3 -- return $ out `B.append` Data.ByteArray.convert auth --module Crypto.Cipher.ChaChaPoly1305 -- | A ChaChaPoly1305 State. -- -- The state is immutable, and only new state can be created data State -- | Valid Nonce for ChaChaPoly1305. -- -- It can be created with nonce8 or nonce12 data Nonce -- | Nonce smart constructor 12 bytes IV, nonce constructor nonce12 :: ByteArrayAccess iv => iv -> CryptoFailable Nonce -- | 8 bytes IV, nonce constructor nonce8 :: ByteArrayAccess ba => ba -> ba -> CryptoFailable Nonce -- | Increment a nonce incrementNonce :: Nonce -> Nonce -- | Initialize a new ChaChaPoly1305 State -- -- The key length need to be 256 bits, and the nonce procured using -- either nonce8 or nonce12 initialize :: ByteArrayAccess key => key -> Nonce -> CryptoFailable State -- | Append Authenticated Data to the State and return the new modified -- State. -- -- Once no further call to this function need to be make, the user should -- call finalizeAAD appendAAD :: ByteArrayAccess ba => ba -> State -> State -- | Finalize the Authenticated Data and return the finalized State finalizeAAD :: State -> State -- | Encrypt a piece of data and returns the encrypted Data and the updated -- State. encrypt :: ByteArray ba => ba -> State -> (ba, State) -- | Decrypt a piece of data and returns the decrypted Data and the updated -- State. decrypt :: ByteArray ba => ba -> State -> (ba, State) -- | Generate an authentication tag from the State. finalize :: State -> Auth instance Data.ByteArray.Types.ByteArrayAccess Crypto.Cipher.ChaChaPoly1305.Nonce module Crypto.Number.Basic -- | sqrti returns two integers (l,b) so that l <= -- sqrt i <= b. The implementation is quite naive, use an -- approximation for the first number and use a dichotomy algorithm to -- compute the bound relatively efficiently. sqrti :: Integer -> (Integer, Integer) -- | Get the extended GCD of two integer using integer divMod -- -- gcde a b find (x,y,gcd(a,b)) where ax + by = d gcde :: Integer -> Integer -> (Integer, Integer, Integer) -- | Check if a list of integer are all even areEven :: [Integer] -> Bool -- | Compute the binary logarithm of a integer log2 :: Integer -> Int -- | Compute the number of bits for an integer numBits :: Integer -> Int -- | Compute the number of bytes for an integer numBytes :: Integer -> Int -- | This module provides basic arithmetic operations over F₂m. Performance -- is not optimal and it doesn't provide protection against timing -- attacks. The m parameter is implicitly derived from the -- irreducible polynomial where applicable. module Crypto.Number.F2m -- | Binary Polynomial represented by an integer type BinaryPolynomial = Integer -- | Addition over F₂m. This is just a synonym of xor. addF2m :: Integer -> Integer -> Integer -- | 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 -> Integer -> Integer -> Integer -- | 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 -- | Squaring over F₂m. -- -- This function is undefined for negative arguments, because their bit -- representation is platform-dependent. Zero modulus is also prohibited. squareF2m :: BinaryPolynomial -> Integer -> Integer -- | 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 -> Integer -> Integer -- | 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 -- representation is platform-dependent. Zero modulus is also prohibited. invF2m :: BinaryPolynomial -> Integer -> Maybe Integer -- | Division over F₂m. If the dividend doesn't have an inverse it returns -- Nothing. -- -- This function is undefined for negative arguments, because their bit -- representation is platform-dependent. Zero modulus is also prohibited. divF2m :: BinaryPolynomial -> Integer -> Integer -> Maybe Integer module Crypto.Number.ModArithmetic -- | Compute the modular exponentiation of base^exponant using algorithms -- design to avoid side channels and timing measurement -- -- Modulo need to be odd otherwise the normal fast modular exponentiation -- is used. -- -- When used with integer-simple, this function is not different from -- expFast, and thus provide the same unstudied and dubious timing and -- side channels claims. -- -- with GHC 7.10, the powModSecInteger is missing from integer-gmp (which -- is now integer-gmp2), so is has the same security as old ghc version. expSafe :: Integer -> Integer -> Integer -> Integer -- | Compute the modular exponentiation of base^exponant using the fastest -- algorithm without any consideration for hiding parameters. -- -- Use this function when all the parameters are public, otherwise -- expSafe should be prefered. expFast :: Integer -> Integer -> Integer -> Integer -- | inverse computes the modular inverse as in g^(-1) mod -- m. inverse :: Integer -> Integer -> Maybe Integer -- | Compute the modular inverse of two coprime numbers. This is equivalent -- to inverse except that the result is known to exists. -- -- If the numbers are not defined as coprime, this function will raise a -- CoprimesAssertionError. inverseCoprimes :: Integer -> Integer -> Integer instance GHC.Show.Show Crypto.Number.ModArithmetic.CoprimesAssertionError instance GHC.Exception.Exception Crypto.Number.ModArithmetic.CoprimesAssertionError -- | Fast serialization primitives for integer using raw pointers module Crypto.Number.Serialize.Internal -- | 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 -- | Similar to i2osp, except it will pad any remaining space with -- zero. i2ospOf :: Integer -> Ptr Word8 -> Int -> IO Int -- | Transform a big endian binary integer representation pointed by a -- pointer and a size into an integer os2ip :: Ptr Word8 -> Int -> IO Integer -- | Fast serialization primitives for integer module Crypto.Number.Serialize -- | 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 :: ByteArray ba => Integer -> ba -- | os2ip converts a byte string into a positive integer. os2ip :: ByteArrayAccess ba => ba -> Integer -- | 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 :: ByteArray ba => Int -> Integer -> Maybe ba -- | 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 the -- size (example the RSA modulo n). i2ospOf_ :: ByteArray ba => Int -> Integer -> ba -- | One-time password implementation as defined by the HOTP and -- TOTP specifications. -- -- Both implementations use a shared key between the client and the -- server. HOTP passwords are based on a synchronized counter. TOTP -- passwords use the same approach but calculate the counter as a number -- of time steps from the Unix epoch to the current time, thus requiring -- that both client and server have synchronized clocks. -- -- Probably the best-known use of TOTP is in Google's 2-factor -- authentication. -- -- The TOTP API doesn't depend on any particular time package, so the -- user needs to supply the current OTPTime value, based on the -- system time. For example, using the hourglass package, you -- could create a getOTPTime function: -- --
-- >>> import Time.System -- -- >>> import Time.Types -- -- >>> -- -- >>> let getOTPTime = timeCurrent >>= \(Elapsed t) -> return (fromIntegral t :: OTPTime) ---- -- Or if you prefer, the time package could be used: -- --
-- >>> import Data.Time.Clock.POSIX -- -- >>> -- -- >>> let getOTPTime = getPOSIXTime >>= \t -> return (floor t :: OTPTime) --module Crypto.OTP -- | A one-time password which is a sequence of 4 to 9 digits. type OTP = Word32 -- | The strength of the calculated HOTP value, namely the number of digits -- (between 4 and 9) in the extracted value. data OTPDigits OTP4 :: OTPDigits OTP5 :: OTPDigits OTP6 :: OTPDigits OTP7 :: OTPDigits OTP8 :: OTPDigits OTP9 :: OTPDigits -- | An integral time value in seconds. type OTPTime = Word64 hotp :: forall hash key. (HashAlgorithm hash, ByteArrayAccess key) => hash -> OTPDigits -> key -> Word64 -> OTP -- | Attempt to resynchronize the server's counter value with the client, -- given a sequence of HOTP values. resynchronize :: (HashAlgorithm hash, ByteArrayAccess key) => hash -> OTPDigits -> Word16 -> key -> Word64 -> (OTP, [OTP]) -> Maybe Word64 -- | Calculate a totp value for the given time. totp :: (HashAlgorithm hash, ByteArrayAccess key) => TOTPParams hash -> key -> OTPTime -> OTP -- | Check a supplied TOTP value is valid for the given time, within the -- window defined by the skew parameter. totpVerify :: (HashAlgorithm hash, ByteArrayAccess key) => TOTPParams hash -> key -> OTPTime -> OTP -> Bool data TOTPParams h data ClockSkew NoSkew :: ClockSkew OneStep :: ClockSkew TwoSteps :: ClockSkew ThreeSteps :: ClockSkew FourSteps :: ClockSkew -- | The default TOTP configuration. defaultTOTPParams :: TOTPParams SHA1 -- | Create a TOTP configuration with customized parameters. mkTOTPParams :: (HashAlgorithm hash) => hash -> OTPTime -> Word16 -> OTPDigits -> ClockSkew -> Either String (TOTPParams hash) instance GHC.Show.Show h => GHC.Show.Show (Crypto.OTP.TOTPParams h) instance GHC.Show.Show Crypto.OTP.ClockSkew instance GHC.Enum.Enum Crypto.OTP.ClockSkew instance GHC.Show.Show Crypto.OTP.OTPDigits -- | References: https://tools.ietf.org/html/rfc5915 module Crypto.PubKey.ECC.Types -- | Define either a binary curve or a prime curve. data Curve -- | 𝔽(2^m) CurveF2m :: CurveBinary -> Curve -- | 𝔽p CurveFP :: CurvePrime -> Curve -- | Define a point on a curve. data Point Point :: Integer -> Integer -> Point -- | Point at Infinity PointO :: Point -- | ECC Public Point type PublicPoint = Point -- | ECC Private Number type PrivateNumber = Integer -- | Define an elliptic curve in 𝔽(2^m). The firt parameter is the Integer -- representatioin of the irreducible polynomial f(x). data CurveBinary CurveBinary :: Integer -> CurveCommon -> CurveBinary -- | Define an elliptic curve in 𝔽p. The first parameter is the Prime -- Number. data CurvePrime CurvePrime :: Integer -> CurveCommon -> CurvePrime -- | Parameters in common between binary and prime curves. common_curve :: Curve -> CurveCommon -- | get the size of the curve in bits curveSizeBits :: Curve -> Int -- | Irreducible polynomial representing the characteristic of a -- CurveBinary. ecc_fx :: CurveBinary -> Integer -- | Prime number representing the characteristic of a CurvePrime. ecc_p :: CurvePrime -> Integer -- | Define common parameters in a curve definition of the form: y^2 = x^3 -- + ax + b. data CurveCommon CurveCommon :: Integer -> Integer -> Point -> Integer -> Integer -> CurveCommon -- | curve parameter a [ecc_a] :: CurveCommon -> Integer -- | curve parameter b [ecc_b] :: CurveCommon -> Integer -- | base point [ecc_g] :: CurveCommon -> Point -- | order of G [ecc_n] :: CurveCommon -> Integer -- | cofactor [ecc_h] :: CurveCommon -> Integer -- | Define names for known recommended curves. data CurveName SEC_p112r1 :: CurveName SEC_p112r2 :: CurveName SEC_p128r1 :: CurveName SEC_p128r2 :: CurveName SEC_p160k1 :: CurveName SEC_p160r1 :: CurveName SEC_p160r2 :: CurveName SEC_p192k1 :: CurveName SEC_p192r1 :: CurveName SEC_p224k1 :: CurveName SEC_p224r1 :: CurveName SEC_p256k1 :: CurveName SEC_p256r1 :: CurveName SEC_p384r1 :: CurveName SEC_p521r1 :: CurveName SEC_t113r1 :: CurveName SEC_t113r2 :: CurveName SEC_t131r1 :: CurveName SEC_t131r2 :: CurveName SEC_t163k1 :: CurveName SEC_t163r1 :: CurveName SEC_t163r2 :: CurveName SEC_t193r1 :: CurveName SEC_t193r2 :: CurveName SEC_t233k1 :: CurveName SEC_t233r1 :: CurveName SEC_t239k1 :: CurveName SEC_t283k1 :: CurveName SEC_t283r1 :: CurveName SEC_t409k1 :: CurveName SEC_t409r1 :: CurveName SEC_t571k1 :: CurveName SEC_t571r1 :: CurveName -- | Get the curve definition associated with a recommended known curve -- name. getCurveByName :: CurveName -> Curve instance Data.Data.Data Crypto.PubKey.ECC.Types.CurveName instance GHC.Enum.Bounded Crypto.PubKey.ECC.Types.CurveName instance GHC.Enum.Enum Crypto.PubKey.ECC.Types.CurveName instance GHC.Classes.Ord Crypto.PubKey.ECC.Types.CurveName instance GHC.Classes.Eq Crypto.PubKey.ECC.Types.CurveName instance GHC.Read.Read Crypto.PubKey.ECC.Types.CurveName instance GHC.Show.Show Crypto.PubKey.ECC.Types.CurveName instance Data.Data.Data Crypto.PubKey.ECC.Types.Curve instance GHC.Classes.Eq Crypto.PubKey.ECC.Types.Curve instance GHC.Read.Read Crypto.PubKey.ECC.Types.Curve instance GHC.Show.Show Crypto.PubKey.ECC.Types.Curve instance Data.Data.Data Crypto.PubKey.ECC.Types.CurveBinary instance GHC.Classes.Eq Crypto.PubKey.ECC.Types.CurveBinary instance GHC.Read.Read Crypto.PubKey.ECC.Types.CurveBinary instance GHC.Show.Show Crypto.PubKey.ECC.Types.CurveBinary instance Data.Data.Data Crypto.PubKey.ECC.Types.CurvePrime instance GHC.Classes.Eq Crypto.PubKey.ECC.Types.CurvePrime instance GHC.Read.Read Crypto.PubKey.ECC.Types.CurvePrime instance GHC.Show.Show Crypto.PubKey.ECC.Types.CurvePrime instance Data.Data.Data Crypto.PubKey.ECC.Types.CurveCommon instance GHC.Classes.Eq Crypto.PubKey.ECC.Types.CurveCommon instance GHC.Read.Read Crypto.PubKey.ECC.Types.CurveCommon instance GHC.Show.Show Crypto.PubKey.ECC.Types.CurveCommon instance Data.Data.Data Crypto.PubKey.ECC.Types.Point instance GHC.Classes.Eq Crypto.PubKey.ECC.Types.Point instance GHC.Read.Read Crypto.PubKey.ECC.Types.Point instance GHC.Show.Show Crypto.PubKey.ECC.Types.Point instance Control.DeepSeq.NFData Crypto.PubKey.ECC.Types.CurveBinary instance Control.DeepSeq.NFData Crypto.PubKey.ECC.Types.Point module Crypto.PubKey.MaskGenFunction -- | Represent a mask generation algorithm type MaskGenAlgorithm seed output = seed seed -> Int length to generate -> output -- | Mask generation algorithm MGF1 mgf1 :: (ByteArrayAccess seed, ByteArray output, HashAlgorithm hashAlg) => hashAlg -> seed -> Int -> output module Crypto.PubKey.RSA.Types -- | error possible during encryption, decryption or signing. data Error -- | the message to decrypt is not of the correct size (need to be == -- private_size) MessageSizeIncorrect :: Error -- | the message to encrypt is too long MessageTooLong :: Error -- | the message decrypted doesn't have a PKCS15 structure (0 2 .. 0 msg) MessageNotRecognized :: Error -- | the message's digest is too long SignatureTooLong :: Error -- | some parameters lead to breaking assumptions. InvalidParameters :: Error -- | Blinder which is used to obfuscate the timing of the decryption -- primitive (used by decryption and signing). data Blinder Blinder :: !Integer -> !Integer -> Blinder -- | Represent a RSA public key data PublicKey PublicKey :: Int -> Integer -> Integer -> PublicKey -- | size of key in bytes [public_size] :: PublicKey -> Int -- | public p*q [public_n] :: PublicKey -> Integer -- | public exponant e [public_e] :: PublicKey -> Integer -- | Represent a RSA private key. -- -- Only the pub, d fields are mandatory to fill. -- -- p, q, dP, dQ, qinv are by-product during RSA generation, but are -- useful to record here to speed up massively the decrypt and sign -- operation. -- -- implementations can leave optional fields to 0. data PrivateKey PrivateKey :: PublicKey -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> PrivateKey -- | public part of a private key (size, n and e) [private_pub] :: PrivateKey -> PublicKey -- | private exponant d [private_d] :: PrivateKey -> Integer -- | p prime number [private_p] :: PrivateKey -> Integer -- | q prime number [private_q] :: PrivateKey -> Integer -- | d mod (p-1) [private_dP] :: PrivateKey -> Integer -- | d mod (q-1) [private_dQ] :: PrivateKey -> Integer -- | q^(-1) mod p [private_qinv] :: PrivateKey -> Integer -- | Represent RSA KeyPair -- -- note the RSA private key contains already an instance of public key -- for efficiency newtype KeyPair KeyPair :: PrivateKey -> KeyPair -- | Public key of a RSA KeyPair toPublicKey :: KeyPair -> PublicKey -- | Private key of a RSA KeyPair toPrivateKey :: KeyPair -> PrivateKey -- | get the size in bytes from a private key private_size :: PrivateKey -> Int -- | get n from a private key private_n :: PrivateKey -> Integer -- | get e from a private key private_e :: PrivateKey -> Integer instance Control.DeepSeq.NFData Crypto.PubKey.RSA.Types.KeyPair instance Data.Data.Data Crypto.PubKey.RSA.Types.KeyPair instance GHC.Classes.Eq Crypto.PubKey.RSA.Types.KeyPair instance GHC.Read.Read Crypto.PubKey.RSA.Types.KeyPair instance GHC.Show.Show Crypto.PubKey.RSA.Types.KeyPair instance Data.Data.Data Crypto.PubKey.RSA.Types.PrivateKey instance GHC.Classes.Eq Crypto.PubKey.RSA.Types.PrivateKey instance GHC.Read.Read Crypto.PubKey.RSA.Types.PrivateKey instance GHC.Show.Show Crypto.PubKey.RSA.Types.PrivateKey instance Data.Data.Data Crypto.PubKey.RSA.Types.PublicKey instance GHC.Classes.Eq Crypto.PubKey.RSA.Types.PublicKey instance GHC.Read.Read Crypto.PubKey.RSA.Types.PublicKey instance GHC.Show.Show Crypto.PubKey.RSA.Types.PublicKey instance GHC.Classes.Eq Crypto.PubKey.RSA.Types.Error instance GHC.Show.Show Crypto.PubKey.RSA.Types.Error instance GHC.Classes.Eq Crypto.PubKey.RSA.Types.Blinder instance GHC.Show.Show Crypto.PubKey.RSA.Types.Blinder instance Control.DeepSeq.NFData Crypto.PubKey.RSA.Types.PrivateKey instance Control.DeepSeq.NFData Crypto.PubKey.RSA.Types.PublicKey module Crypto.PubKey.RSA.Prim -- | Compute the RSA decrypt primitive. if the p and q numbers are -- available, then dpFast is used otherwise, we use dpSlow which only -- need d and n. dp :: ByteArray ba => Maybe Blinder -> PrivateKey -> ba -> ba -- | Compute the RSA encrypt primitive ep :: ByteArray ba => PublicKey -> ba -> ba module Crypto.Random.Entropy.Unsafe -- | Refill the entropy in a buffer -- -- Call each entropy backend in turn until the buffer has been -- replenished. -- -- If the buffer cannot be refill after 3 loopings, this will raise an -- User Error exception replenish :: Int -> [EntropyBackend] -> Ptr Word8 -> IO () -- | Any Entropy Backend data EntropyBackend -- | All supported backends supportedBackends :: [IO (Maybe EntropyBackend)] -- | Gather randomness from an open handle gatherBackend :: EntropyBackend -> Ptr Word8 -> Int -> IO Int module Crypto.Random.Entropy -- | Get some entropy from the system source of entropy getEntropy :: ByteArray byteArray => Int -> IO byteArray module Crypto.Random.EntropyPool -- | Pool of Entropy. Contains a self-mutating pool of entropy, that is -- always guaranteed to contain data. data EntropyPool -- | Create a new entropy pool with a default size. -- -- While you can create as many entropy pools as you want, the pool can -- be shared between multiples RNGs. createEntropyPool :: IO EntropyPool -- | Create a new entropy pool of a specific size -- -- While you can create as many entropy pools as you want, the pool can -- be shared between multiples RNGs. createEntropyPoolWith :: Int -> [EntropyBackend] -> IO EntropyPool -- | Grab a chunk of entropy from the entropy pool. getEntropyFrom :: ByteArray byteArray => EntropyPool -> Int -> IO byteArray module Crypto.Random.Types -- | A monad constraint that allows to generate random bytes class (Functor m, Monad m) => MonadRandom m getRandomBytes :: (MonadRandom m, ByteArray byteArray) => Int -> m byteArray -- | A simple Monad class very similar to a State Monad with the state -- being a DRG. data MonadPseudoRandom gen a -- | A Deterministic Random Generator (DRG) class class DRG gen -- | Generate N bytes of randomness from a DRG randomBytesGenerate :: (DRG gen, ByteArray byteArray) => Int -> gen -> (byteArray, gen) -- | Run a pure computation with a Deterministic Random Generator in the -- MonadPseudoRandom withDRG :: DRG gen => gen -> MonadPseudoRandom gen a -> (a, gen) instance Crypto.Random.Types.DRG gen => GHC.Base.Functor (Crypto.Random.Types.MonadPseudoRandom gen) instance Crypto.Random.Types.DRG gen => GHC.Base.Applicative (Crypto.Random.Types.MonadPseudoRandom gen) instance Crypto.Random.Types.DRG gen => GHC.Base.Monad (Crypto.Random.Types.MonadPseudoRandom gen) instance Crypto.Random.Types.DRG gen => Crypto.Random.Types.MonadRandom (Crypto.Random.Types.MonadPseudoRandom gen) instance Crypto.Random.Types.MonadRandom GHC.Types.IO module Crypto.Random -- | ChaCha Deterministic Random Generator data ChaChaDRG -- | A referentially transparent System representation of the random -- evaluated out of the system. -- -- Holding onto a specific DRG means that all the already evaluated bytes -- will be consistently replayed. -- -- There's no need to reseed this DRG, as only pure entropy is -- represented here. data SystemDRG data Seed -- | Create a new Seed from system entropy seedNew :: MonadRandom randomly => randomly Seed -- | Convert an integer to a Seed seedFromInteger :: Integer -> Seed -- | Convert a Seed to an integer seedToInteger :: Seed -> Integer -- | Convert a binary to a seed seedFromBinary :: ByteArrayAccess b => b -> CryptoFailable Seed -- | Grab one instance of the System DRG getSystemDRG :: IO SystemDRG -- | Create a new DRG from system entropy drgNew :: MonadRandom randomly => randomly ChaChaDRG -- | Create a new DRG from a seed drgNewSeed :: Seed -> ChaChaDRG -- | Create a new DRG from 5 Word64. -- -- This is a convenient interface to create deterministic interface for -- quickcheck style testing. -- -- It can also be used in other contexts provided the input has been -- properly randomly generated. drgNewTest :: (Word64, Word64, Word64, Word64, Word64) -> ChaChaDRG -- | Run a pure computation with a Deterministic Random Generator in the -- MonadPseudoRandom withDRG :: DRG gen => gen -> MonadPseudoRandom gen a -> (a, gen) -- | Generate len random bytes and mapped the bytes to the function -- f. -- -- This is equivalent to use Control.Arrow first with -- randomBytesGenerate withRandomBytes :: (ByteArray ba, DRG g) => g -> Int -> (ba -> a) -> (a, g) -- | A Deterministic Random Generator (DRG) class class DRG gen -- | Generate N bytes of randomness from a DRG randomBytesGenerate :: (DRG gen, ByteArray byteArray) => Int -> gen -> (byteArray, gen) -- | A monad constraint that allows to generate random bytes class (Functor m, Monad m) => MonadRandom m getRandomBytes :: (MonadRandom m, ByteArray byteArray) => Int -> m byteArray -- | A simple Monad class very similar to a State Monad with the state -- being a DRG. data MonadPseudoRandom gen a instance Data.ByteArray.Types.ByteArrayAccess Crypto.Random.Seed -- | Ed448 support -- -- Internally uses Decaf point compression to omit the cofactor and -- implementation by Mike Hamburg. Externally API and data types are -- compatible with the encoding specified in RFC 8032. module Crypto.PubKey.Ed448 -- | An Ed448 Secret key data SecretKey -- | An Ed448 public key data PublicKey -- | An Ed448 signature data Signature -- | A public key is 57 bytes publicKeySize :: Int -- | A secret key is 57 bytes secretKeySize :: Int -- | A signature is 114 bytes signatureSize :: Int -- | Try to build a signature from a bytearray signature :: ByteArrayAccess ba => ba -> CryptoFailable Signature -- | Try to build a public key from a bytearray publicKey :: ByteArrayAccess ba => ba -> CryptoFailable PublicKey -- | Try to build a secret key from a bytearray secretKey :: ByteArrayAccess ba => ba -> CryptoFailable SecretKey -- | Create a public key from a secret key toPublic :: SecretKey -> PublicKey -- | Sign a message using the key pair sign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> Signature -- | Verify a message verify :: ByteArrayAccess ba => PublicKey -> ba -> Signature -> Bool -- | Generate a secret key generateSecretKey :: MonadRandom m => m SecretKey instance Control.DeepSeq.NFData Crypto.PubKey.Ed448.Signature instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Ed448.Signature instance GHC.Classes.Eq Crypto.PubKey.Ed448.Signature instance GHC.Show.Show Crypto.PubKey.Ed448.Signature instance Control.DeepSeq.NFData Crypto.PubKey.Ed448.PublicKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Ed448.PublicKey instance GHC.Classes.Eq Crypto.PubKey.Ed448.PublicKey instance GHC.Show.Show Crypto.PubKey.Ed448.PublicKey instance Control.DeepSeq.NFData Crypto.PubKey.Ed448.SecretKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Ed448.SecretKey instance GHC.Classes.Eq Crypto.PubKey.Ed448.SecretKey instance GHC.Show.Show Crypto.PubKey.Ed448.SecretKey -- | Ed25519 support module Crypto.PubKey.Ed25519 -- | An Ed25519 Secret key data SecretKey -- | An Ed25519 public key data PublicKey -- | An Ed25519 signature data Signature -- | A public key is 32 bytes publicKeySize :: Int -- | A secret key is 32 bytes secretKeySize :: Int -- | A signature is 64 bytes signatureSize :: Int -- | Try to build a signature from a bytearray signature :: ByteArrayAccess ba => ba -> CryptoFailable Signature -- | Try to build a public key from a bytearray publicKey :: ByteArrayAccess ba => ba -> CryptoFailable PublicKey -- | Try to build a secret key from a bytearray secretKey :: ByteArrayAccess ba => ba -> CryptoFailable SecretKey -- | Create a public key from a secret key toPublic :: SecretKey -> PublicKey -- | Sign a message using the key pair sign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> Signature -- | Verify a message verify :: ByteArrayAccess ba => PublicKey -> ba -> Signature -> Bool -- | Generate a secret key generateSecretKey :: MonadRandom m => m SecretKey instance Control.DeepSeq.NFData Crypto.PubKey.Ed25519.Signature instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Ed25519.Signature instance GHC.Classes.Eq Crypto.PubKey.Ed25519.Signature instance GHC.Show.Show Crypto.PubKey.Ed25519.Signature instance Control.DeepSeq.NFData Crypto.PubKey.Ed25519.PublicKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Ed25519.PublicKey instance GHC.Classes.Eq Crypto.PubKey.Ed25519.PublicKey instance GHC.Show.Show Crypto.PubKey.Ed25519.PublicKey instance Control.DeepSeq.NFData Crypto.PubKey.Ed25519.SecretKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Ed25519.SecretKey instance GHC.Classes.Eq Crypto.PubKey.Ed25519.SecretKey instance GHC.Show.Show Crypto.PubKey.Ed25519.SecretKey -- | P256 support module Crypto.PubKey.ECC.P256 -- | A P256 scalar data Scalar -- | A P256 point data Point -- | Get the base point for the P256 Curve pointBase :: Point -- | Add a point to another point pointAdd :: Point -> Point -> Point -- | Negate a point pointNegate :: Point -> Point -- | Multiply a point by a scalar -- -- warning: variable time pointMul :: Scalar -> Point -> Point -- | Similar to pointMul, serializing the x coordinate as binary. -- When scalar is multiple of point order the result is all zero. pointDh :: ByteArray binary => Scalar -> Point -> binary -- | multiply the point p with n2 and add a lifted to curve value -- @n1 -- --
-- n1 * G + n2 * p ---- -- warning: variable time pointsMulVarTime :: Scalar -> Scalar -> Point -> Point -- | Check if a Point is valid pointIsValid :: Point -> Bool -- | Lift to curve a scalar -- -- Using the curve generator as base point compute: -- --
-- scalar * G --toPoint :: Scalar -> Point -- | Convert a point to (x,y) Integers pointToIntegers :: Point -> (Integer, Integer) -- | Convert from (x,y) Integers to a point pointFromIntegers :: (Integer, Integer) -> Point -- | Convert a point to a binary representation pointToBinary :: ByteArray ba => Point -> ba -- | Convert from binary to a valid point pointFromBinary :: ByteArrayAccess ba => ba -> CryptoFailable Point -- | Convert from binary to a point, possibly invalid unsafePointFromBinary :: ByteArrayAccess ba => ba -> CryptoFailable Point -- | Generate a randomly generated new scalar scalarGenerate :: MonadRandom randomly => randomly Scalar -- | The scalar representing 0 scalarZero :: Scalar -- | Check if the scalar is 0 scalarIsZero :: Scalar -> Bool -- | Perform addition between two scalars -- --
-- a + b --scalarAdd :: Scalar -> Scalar -> Scalar -- | Perform subtraction between two scalars -- --
-- a - b --scalarSub :: Scalar -> Scalar -> Scalar -- | Give the inverse of the scalar -- --
-- 1 / a ---- -- warning: variable time scalarInv :: Scalar -> Scalar -- | Compare 2 Scalar scalarCmp :: Scalar -> Scalar -> Ordering -- | convert a scalar from binary scalarFromBinary :: ByteArrayAccess ba => ba -> CryptoFailable Scalar -- | convert a scalar to binary scalarToBinary :: ByteArray ba => Scalar -> ba -- | Convert from an Integer to a P256 Scalar scalarFromInteger :: Integer -> CryptoFailable Scalar -- | Convert from a P256 Scalar to an Integer scalarToInteger :: Scalar -> Integer instance Control.DeepSeq.NFData Crypto.PubKey.ECC.P256.Point instance GHC.Classes.Eq Crypto.PubKey.ECC.P256.Point instance GHC.Show.Show Crypto.PubKey.ECC.P256.Point instance Control.DeepSeq.NFData Crypto.PubKey.ECC.P256.Scalar instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.ECC.P256.Scalar instance GHC.Classes.Eq Crypto.PubKey.ECC.P256.Scalar instance GHC.Show.Show Crypto.PubKey.ECC.P256.Scalar -- | Curve448 support -- -- Internally uses Decaf point compression to omit the cofactor and -- implementation by Mike Hamburg. Externally API and data types are -- compatible with the encoding specified in RFC 7748. module Crypto.PubKey.Curve448 -- | A Curve448 Secret key data SecretKey -- | A Curve448 public key data PublicKey -- | A Curve448 Diffie Hellman secret related to a public key and a secret -- key. data DhSecret -- | Create a DhSecret from a bytearray object dhSecret :: ByteArrayAccess b => b -> CryptoFailable DhSecret -- | Try to build a public key from a bytearray publicKey :: ByteArrayAccess bs => bs -> CryptoFailable PublicKey -- | Try to build a secret key from a bytearray secretKey :: ByteArrayAccess bs => bs -> CryptoFailable SecretKey -- | Compute the Diffie Hellman secret from a public key and a secret key. -- -- This implementation may return an all-zero value as it does not check -- for the condition. dh :: PublicKey -> SecretKey -> DhSecret -- | Create a public key from a secret key toPublic :: SecretKey -> PublicKey -- | Generate a secret key. generateSecretKey :: MonadRandom m => m SecretKey instance Control.DeepSeq.NFData Crypto.PubKey.Curve448.DhSecret instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Curve448.DhSecret instance GHC.Classes.Eq Crypto.PubKey.Curve448.DhSecret instance GHC.Show.Show Crypto.PubKey.Curve448.DhSecret instance Control.DeepSeq.NFData Crypto.PubKey.Curve448.PublicKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Curve448.PublicKey instance GHC.Classes.Eq Crypto.PubKey.Curve448.PublicKey instance GHC.Show.Show Crypto.PubKey.Curve448.PublicKey instance Control.DeepSeq.NFData Crypto.PubKey.Curve448.SecretKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Curve448.SecretKey instance GHC.Classes.Eq Crypto.PubKey.Curve448.SecretKey instance GHC.Show.Show Crypto.PubKey.Curve448.SecretKey -- | Curve25519 support module Crypto.PubKey.Curve25519 -- | A Curve25519 Secret key data SecretKey -- | A Curve25519 public key data PublicKey -- | A Curve25519 Diffie Hellman secret related to a public key and a -- secret key. data DhSecret -- | Create a DhSecret from a bytearray object dhSecret :: ByteArrayAccess b => b -> CryptoFailable DhSecret -- | Try to build a public key from a bytearray publicKey :: ByteArrayAccess bs => bs -> CryptoFailable PublicKey -- | Try to build a secret key from a bytearray secretKey :: ByteArrayAccess bs => bs -> CryptoFailable SecretKey -- | Compute the Diffie Hellman secret from a public key and a secret key. -- -- This implementation may return an all-zero value as it does not check -- for the condition. dh :: PublicKey -> SecretKey -> DhSecret -- | Create a public key from a secret key toPublic :: SecretKey -> PublicKey -- | Generate a secret key. generateSecretKey :: MonadRandom m => m SecretKey instance Control.DeepSeq.NFData Crypto.PubKey.Curve25519.DhSecret instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Curve25519.DhSecret instance GHC.Classes.Eq Crypto.PubKey.Curve25519.DhSecret instance GHC.Show.Show Crypto.PubKey.Curve25519.DhSecret instance Control.DeepSeq.NFData Crypto.PubKey.Curve25519.PublicKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Curve25519.PublicKey instance GHC.Classes.Eq Crypto.PubKey.Curve25519.PublicKey instance GHC.Show.Show Crypto.PubKey.Curve25519.PublicKey instance Control.DeepSeq.NFData Crypto.PubKey.Curve25519.SecretKey instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.Curve25519.SecretKey instance GHC.Classes.Eq Crypto.PubKey.Curve25519.SecretKey instance GHC.Show.Show Crypto.PubKey.Curve25519.SecretKey -- | Password encoding and validation using bcrypt. -- -- Example usage: -- --
-- >>> import Crypto.KDF.BCrypt (hashPassword, validatePassword) -- -- >>> import qualified Data.ByteString.Char8 as B -- -- >>> -- -- >>> let bcryptHash = B.pack "$2a$10$MJJifxfaqQmbx1Mhsq3oq.YmMmfNhkyW4s/MS3K5rIMVfB7w0Q/OW" -- -- >>> let password = B.pack "password" -- -- >>> validatePassword password bcryptHash -- -- >>> True -- -- >>> let otherPassword = B.pack "otherpassword" -- -- >>> otherHash <- hashPassword 12 otherPasssword :: IO B.ByteString -- -- >>> validatePassword otherPassword otherHash -- -- >>> True ---- -- See -- https://www.usenix.org/conference/1999-usenix-annual-technical-conference/future-adaptable-password-scheme -- for details of the original algorithm. -- -- The functions hashPassword and validatePassword -- should be all that most users need. -- -- Hashes are strings of the form -- $2a$10$MJJifxfaqQmbx1Mhsq3oq.YmMmfNhkyW4sMS3K5rIMVfB7w0QOW -- which encode a version number, an integer cost parameter and the -- concatenated salt and hash bytes (each separately Base64 encoded. -- Incrementing the cost parameter approximately doubles the time taken -- to calculate the hash. -- -- The different version numbers evolved to account for bugs in the -- standard C implementations. They don't represent different versions of -- the algorithm itself and in most cases should produce identical -- results. The most up to date version is 2b and this -- implementation uses the 2b version prefix, but will also -- attempt to validate against hashes with versions 2a and -- 2y. Version 2 or 2x will be rejected. No -- attempt is made to differentiate between the different versions when -- validating a password, but in practice this shouldn't cause any -- problems if passwords are UTF-8 encoded (which they should be) and -- less than 256 characters long. -- -- The cost parameter can be between 4 and 31 inclusive, but anything -- less than 10 is probably not strong enough. High values may be -- prohibitively slow depending on your hardware. Choose the highest -- value you can without having an unacceptable impact on your users. The -- cost parameter can also be varied depending on the account, since it -- is unique to an individual hash. module Crypto.KDF.BCrypt -- | Create a bcrypt hash for a password with a provided cost value. -- Typically used to create a hash when a new user account is registered -- or when a user changes their password. -- -- Each increment of the cost approximately doubles the time taken. The -- 16 bytes of random salt will be generated internally. hashPassword :: (MonadRandom m, ByteArray password, ByteArray hash) => Int -> password -> m hash -- | Check a password against a stored bcrypt hash when authenticating a -- user. -- -- Returns False if the password doesn't match the hash, or if -- the hash is invalid or an unsupported version. validatePassword :: (ByteArray password, ByteArray hash) => password -> hash -> Bool -- | Check a password against a bcrypt hash -- -- As for validatePassword but will provide error information if -- the hash is invalid or an unsupported version. validatePasswordEither :: (ByteArray password, ByteArray hash) => password -> hash -> Either String Bool -- | Create a bcrypt hash for a password with a provided cost value and -- salt. -- -- Cost value under 4 will be automatically adjusted back to 10 for -- safety reason. bcrypt :: (ByteArray salt, ByteArray password, ByteArray output) => Int -> salt -> password -> output -- | Arithmetic primitives over curve edwards25519. -- -- Twisted Edwards curves are a familly of elliptic curves allowing -- complete addition formulas without any special case and no point at -- infinity. Curve edwards25519 is based on prime 2^255 - 19 for -- efficient implementation. Equation and parameters are given in RFC -- 7748. -- -- This module provides types and primitive operations that are useful to -- implement cryptographic schemes based on curve edwards25519: -- --
-- pointHasPrimeOrder p = pointNegate p == pointMul l_minus_one p --pointHasPrimeOrder :: Point -> Bool -- | Multiplies a scalar with the curve base point. toPoint :: Scalar -> Point -- | Add two scalars. scalarAdd :: Scalar -> Scalar -> Scalar -- | Multiply two scalars. scalarMul :: Scalar -> Scalar -> Scalar -- | Negate a point. pointNegate :: Point -> Point -- | Add two points. pointAdd :: Point -> Point -> Point -- | Add a point to itself. -- --
-- pointDouble p = pointAdd p p --pointDouble :: Point -> Point -- | Scalar multiplication over curve edwards25519. -- -- Note: when the scalar had reduction modulo L and the input point has a -- torsion component, the output point may not be in the expected -- subgroup. pointMul :: Scalar -> Point -> Point -- | Multiply a point by h = 8. -- --
-- pointMulByCofactor p = pointMul scalar_8 p --pointMulByCofactor :: Point -> Point -- | Multiply the point p with s2 and add a lifted to -- curve value s1. -- --
-- pointsMulVarTime s1 s2 p = pointAdd (toPoint s1) (pointMul s2 p) ---- -- WARNING: variable time pointsMulVarTime :: Scalar -> Scalar -> Point -> Point instance Control.DeepSeq.NFData Crypto.ECC.Edwards25519.Point instance Control.DeepSeq.NFData Crypto.ECC.Edwards25519.Scalar instance GHC.Show.Show Crypto.ECC.Edwards25519.Scalar instance GHC.Show.Show Crypto.ECC.Edwards25519.Point instance GHC.Classes.Eq Crypto.ECC.Edwards25519.Point instance GHC.Classes.Eq Crypto.ECC.Edwards25519.Scalar module Crypto.Number.Generate -- | Top bits policy when generating a number data GenTopPolicy -- | set the highest bit SetHighest :: GenTopPolicy -- | set the two highest bit SetTwoHighest :: GenTopPolicy -- | Generate a number for a specific size of bits, and optionaly set -- bottom and top bits -- -- If the top bit policy is Nothing, then nothing is done on the -- highest bit (it's whatever the random generator set). -- -- If @generateOdd is set to True, then the number generated is -- guaranteed to be odd. Otherwise it will be whatever is generated generateParams :: MonadRandom m => Int -> Maybe GenTopPolicy -> Bool -> m Integer -- | Generate a positive integer x, s.t. 0 <= x < range generateMax :: MonadRandom m => Integer -> m Integer -- | generate a number between the inclusive bound [low,high]. generateBetween :: MonadRandom m => Integer -> Integer -> m Integer instance GHC.Classes.Eq Crypto.Number.Generate.GenTopPolicy instance GHC.Show.Show Crypto.Number.Generate.GenTopPolicy -- | Elliptic Curve Arithmetic. -- -- WARNING: These functions are vulnerable to timing attacks. module Crypto.PubKey.ECC.Prim -- | Generate a valid scalar for a specific Curve scalarGenerate :: MonadRandom randomly => Curve -> randomly PrivateNumber -- | Elliptic Curve point addition. -- -- WARNING: Vulnerable to timing attacks. pointAdd :: Curve -> Point -> Point -> Point -- | Elliptic Curve point negation: pointNegate c p returns point -- q such that pointAdd c p q == PointO. pointNegate :: Curve -> Point -> Point -- | Elliptic Curve point doubling. -- -- WARNING: Vulnerable to timing attacks. -- -- This perform the following calculation: > lambda = (3 * xp ^ 2 + a) -- / 2 yp > xr = lambda ^ 2 - 2 xp > yr = lambda (xp - xr) - yp -- -- With binary curve: > xp == 0 => P = O > otherwise => > -- s = xp + (yp / xp) > xr = s ^ 2 + s + a > yr = xp ^ 2 + (s+1) * -- xr pointDouble :: Curve -> Point -> Point -- | Elliptic curve point multiplication using the base -- -- WARNING: Vulnerable to timing attacks. pointBaseMul :: Curve -> Integer -> Point -- | Elliptic curve point multiplication (double and add algorithm). -- -- WARNING: Vulnerable to timing attacks. pointMul :: Curve -> Integer -> Point -> Point -- | Elliptic curve double-scalar multiplication (uses Shamir's trick). -- --
-- pointAddTwoMuls c n1 p1 n2 p2 == pointAdd c (pointMul c n1 p1) -- (pointMul c n2 p2) ---- -- WARNING: Vulnerable to timing attacks. pointAddTwoMuls :: Curve -> Integer -> Point -> Integer -> Point -> Point -- | Check if a point is the point at infinity. isPointAtInfinity :: Point -> Bool -- | check if a point is on specific curve -- -- This perform three checks: -- --