-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/
-- | Cryptography Primitives sink
--
-- A repository of cryptographic primitives.
--
--
-- - Symmetric ciphers: AES, DES, 3DES, CAST5, Blowfish, Twofish,
-- Camellia, RC4, Salsa, XSalsa, ChaCha.
-- - Hash: SHA1, SHA2, SHA3, SHAKE, MD2, MD4, MD5, Keccak, Skein,
-- Ripemd, Tiger, Whirlpool, Blake2
-- - MAC: HMAC, KMAC, Poly1305
-- - Asymmetric crypto: DSA, RSA, DH, ECDH, ECDSA, ECC, Curve25519,
-- Curve448, Ed25519, Ed448
-- - Key Derivation Function: PBKDF2, Scrypt, HKDF, Argon2, BCrypt,
-- BCryptPBKDF
-- - Cryptographic Random generation: System Entropy, Deterministic
-- Random Generator
-- - Data related: Anti-Forensic Information Splitter (AFIS)
--
--
-- If anything cryptographic related is missing from here, submit a pull
-- request to have it added. This package strives to be a cryptographic
-- kitchen sink that provides cryptography for everyone.
--
-- Evaluate the security related to your requirements before using.
--
-- Read Crypto.Tutorial for a quick start guide.
@package cryptonite
@version 0.27
-- | Various cryptographic padding commonly used for block ciphers or
-- asymmetric systems.
module Crypto.Data.Padding
-- | Format of padding
data Format
-- | PKCS5: PKCS7 with hardcoded size of 8
PKCS5 :: Format
-- | PKCS7 with padding size between 1 and 255
PKCS7 :: Int -> Format
-- | zero padding with block size
ZERO :: Int -> Format
-- | Apply some pad to a bytearray
pad :: ByteArray byteArray => Format -> byteArray -> byteArray
-- | Try to remove some padding from a bytearray.
unpad :: ByteArray byteArray => Format -> byteArray -> Maybe byteArray
instance GHC.Classes.Eq Crypto.Data.Padding.Format
instance GHC.Show.Show Crypto.Data.Padding.Format
module Crypto.Error
-- | Enumeration of all possible errors that can be found in this library
data CryptoError
CryptoError_KeySizeInvalid :: CryptoError
CryptoError_IvSizeInvalid :: CryptoError
CryptoError_SeedSizeInvalid :: CryptoError
CryptoError_AEADModeNotSupported :: CryptoError
CryptoError_SecretKeySizeInvalid :: CryptoError
CryptoError_SecretKeyStructureInvalid :: CryptoError
CryptoError_PublicKeySizeInvalid :: CryptoError
CryptoError_SharedSecretSizeInvalid :: CryptoError
CryptoError_EcScalarOutOfBounds :: CryptoError
CryptoError_PointSizeInvalid :: CryptoError
CryptoError_PointFormatInvalid :: CryptoError
CryptoError_PointFormatUnsupported :: CryptoError
CryptoError_PointCoordinatesInvalid :: CryptoError
CryptoError_ScalarMultiplicationInvalid :: CryptoError
CryptoError_MacKeyInvalid :: CryptoError
CryptoError_AuthenticationTagSizeInvalid :: CryptoError
CryptoError_PrimeSizeInvalid :: CryptoError
CryptoError_SaltTooSmall :: CryptoError
CryptoError_OutputLengthTooSmall :: CryptoError
CryptoError_OutputLengthTooBig :: CryptoError
-- | A simple Either like type to represent a computation that can fail
--
-- 2 possibles values are:
--
--
-- - CryptoPassed : The computation succeeded, and contains the
-- result of the computation
-- - CryptoFailed : The computation failed, and contains the
-- cryptographic error associated
--
data CryptoFailable a
CryptoPassed :: a -> CryptoFailable a
CryptoFailed :: CryptoError -> CryptoFailable a
-- | Throw an CryptoError as exception on CryptoFailed result, otherwise
-- return the computed value
throwCryptoErrorIO :: CryptoFailable a -> IO a
-- | Same as throwCryptoErrorIO but throw the error asynchronously.
throwCryptoError :: CryptoFailable a -> a
-- | Simple either like combinator for CryptoFailable type
onCryptoFailure :: (CryptoError -> r) -> (a -> r) -> CryptoFailable a -> r
-- | Transform a CryptoFailable to an Either
eitherCryptoError :: CryptoFailable a -> Either CryptoError a
-- | Transform a CryptoFailable to a Maybe
maybeCryptoError :: CryptoFailable a -> Maybe a
-- | Generalized impure cryptographic hash interface
module Crypto.Hash.IO
-- | Class representing hashing algorithms.
--
-- The interface presented here is update in place and lowlevel. the Hash
-- module takes care of hidding the mutable interface properly.
class HashAlgorithm a where {
-- | Associated type for the block size of the hash algorithm
type family HashBlockSize a :: Nat;
-- | Associated type for the digest size of the hash algorithm
type family HashDigestSize a :: Nat;
-- | Associated type for the internal context size of the hash algorithm
type family HashInternalContextSize a :: Nat;
}
-- | 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
-- | Get the size of the context used for a hash algorithm
hashInternalContextSize :: HashAlgorithm a => a -> Int
-- | Initialize a context pointer to the initial state of a hash algorithm
hashInternalInit :: HashAlgorithm a => Ptr (Context a) -> IO ()
-- | Update the context with some raw data
hashInternalUpdate :: HashAlgorithm a => Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
-- | Finalize the context and set the digest raw memory to the right value
hashInternalFinalize :: HashAlgorithm a => Ptr (Context a) -> Ptr (Digest a) -> IO ()
-- | A Mutable hash context
data MutableContext a
-- | Create a new mutable hash context.
--
-- the algorithm used is automatically determined from the return
-- constraint.
hashMutableInit :: HashAlgorithm alg => IO (MutableContext alg)
-- | Create a new mutable hash context.
--
-- The algorithm is explicitely passed as parameter
hashMutableInitWith :: HashAlgorithm alg => alg -> IO (MutableContext alg)
-- | Update a mutable hash context in place
hashMutableUpdate :: (ByteArrayAccess ba, HashAlgorithm a) => MutableContext a -> ba -> IO ()
-- | Finalize a mutable hash context and compute a digest
hashMutableFinalize :: forall a. HashAlgorithm a => MutableContext a -> IO (Digest a)
-- | Reset the mutable context to the initial state of the hash
hashMutableReset :: HashAlgorithm a => MutableContext a -> IO ()
instance Data.ByteArray.Types.ByteArrayAccess (Crypto.Hash.IO.MutableContext a)
-- | Symmetric cipher basic types
module Crypto.Cipher.Types
-- | Symmetric cipher class.
class Cipher cipher
-- | Initialize a cipher context from a key
cipherInit :: (Cipher cipher, ByteArray key) => key -> CryptoFailable cipher
-- | Cipher name
cipherName :: Cipher cipher => cipher -> String
-- | return the size of the key required for this cipher. Some cipher
-- accept any size for key
cipherKeySize :: Cipher cipher => cipher -> KeySizeSpecifier
-- | Symmetric block cipher class
class Cipher cipher => BlockCipher cipher
-- | Return the size of block required for this block cipher
blockSize :: BlockCipher cipher => cipher -> Int
-- | Encrypt blocks
--
-- the input string need to be multiple of the block size
ecbEncrypt :: (BlockCipher cipher, ByteArray ba) => cipher -> ba -> ba
-- | Decrypt blocks
--
-- the input string need to be multiple of the block size
ecbDecrypt :: (BlockCipher cipher, ByteArray ba) => cipher -> ba -> ba
-- | encrypt using the CBC mode.
--
-- input need to be a multiple of the blocksize
cbcEncrypt :: (BlockCipher cipher, ByteArray ba) => cipher -> IV cipher -> ba -> ba
-- | decrypt using the CBC mode.
--
-- input need to be a multiple of the blocksize
cbcDecrypt :: (BlockCipher cipher, ByteArray ba) => cipher -> IV cipher -> ba -> ba
-- | encrypt using the CFB mode.
--
-- input need to be a multiple of the blocksize
cfbEncrypt :: (BlockCipher cipher, ByteArray ba) => cipher -> IV cipher -> ba -> ba
-- | decrypt using the CFB mode.
--
-- input need to be a multiple of the blocksize
cfbDecrypt :: (BlockCipher cipher, ByteArray ba) => cipher -> IV cipher -> ba -> ba
-- | combine using the CTR mode.
--
-- CTR mode produce a stream of randomized data that is combined (by XOR
-- operation) with the input stream.
--
-- encryption and decryption are the same operation.
--
-- input can be of any size
ctrCombine :: (BlockCipher cipher, ByteArray ba) => cipher -> IV cipher -> ba -> ba
-- | Initialize a new AEAD State
--
-- When Nothing is returns, it means the mode is not handled.
aeadInit :: (BlockCipher cipher, ByteArrayAccess iv) => AEADMode -> cipher -> iv -> CryptoFailable (AEAD cipher)
-- | class of block cipher with a 128 bits block size
class BlockCipher cipher => BlockCipher128 cipher
-- | encrypt using the XTS mode.
--
-- input need to be a multiple of the blocksize, and the cipher need to
-- process 128 bits block only
xtsEncrypt :: (BlockCipher128 cipher, ByteArray ba) => (cipher, cipher) -> IV cipher -> DataUnitOffset -> ba -> ba
-- | decrypt using the XTS mode.
--
-- input need to be a multiple of the blocksize, and the cipher need to
-- process 128 bits block only
xtsDecrypt :: (BlockCipher128 cipher, ByteArray ba) => (cipher, cipher) -> IV cipher -> DataUnitOffset -> ba -> ba
-- | Symmetric stream cipher class
class Cipher cipher => StreamCipher cipher
-- | Combine using the stream cipher
streamCombine :: (StreamCipher cipher, ByteArray ba) => cipher -> ba -> (ba, cipher)
-- | Offset inside an XTS data unit, measured in block size.
type DataUnitOffset = Word32
-- | Different specifier for key size in bytes
data KeySizeSpecifier
-- | in the range [min,max]
KeySizeRange :: Int -> Int -> KeySizeSpecifier
-- | one of the specified values
KeySizeEnum :: [Int] -> KeySizeSpecifier
-- | a specific size
KeySizeFixed :: Int -> KeySizeSpecifier
-- | AEAD Mode
data AEADMode
AEAD_OCB :: AEADMode
AEAD_CCM :: Int -> CCM_M -> CCM_L -> AEADMode
AEAD_EAX :: AEADMode
AEAD_CWC :: AEADMode
AEAD_GCM :: AEADMode
data CCM_M
CCM_M4 :: CCM_M
CCM_M6 :: CCM_M
CCM_M8 :: CCM_M
CCM_M10 :: CCM_M
CCM_M12 :: CCM_M
CCM_M14 :: CCM_M
CCM_M16 :: CCM_M
data CCM_L
CCM_L2 :: CCM_L
CCM_L3 :: CCM_L
CCM_L4 :: CCM_L
-- | AEAD Implementation
data AEADModeImpl st
AEADModeImpl :: (forall ba. ByteArrayAccess ba => st -> ba -> st) -> (forall ba. ByteArray ba => st -> ba -> (ba, st)) -> (forall ba. ByteArray ba => st -> ba -> (ba, st)) -> (st -> Int -> AuthTag) -> AEADModeImpl st
[aeadImplAppendHeader] :: AEADModeImpl st -> forall ba. ByteArrayAccess ba => st -> ba -> st
[aeadImplEncrypt] :: AEADModeImpl st -> forall ba. ByteArray ba => st -> ba -> (ba, st)
[aeadImplDecrypt] :: AEADModeImpl st -> forall ba. ByteArray ba => st -> ba -> (ba, st)
[aeadImplFinalize] :: AEADModeImpl st -> st -> Int -> AuthTag
-- | Authenticated Encryption with Associated Data algorithms
data AEAD cipher
AEAD :: AEADModeImpl st -> st -> AEAD cipher
[aeadModeImpl] :: AEAD cipher -> AEADModeImpl st
[aeadState] :: AEAD cipher -> st
-- | Append some header information to an AEAD context
aeadAppendHeader :: ByteArrayAccess aad => AEAD cipher -> aad -> AEAD cipher
-- | Encrypt some data and update the AEAD context
aeadEncrypt :: ByteArray ba => AEAD cipher -> ba -> (ba, AEAD cipher)
-- | Decrypt some data and update the AEAD context
aeadDecrypt :: ByteArray ba => AEAD cipher -> ba -> (ba, AEAD cipher)
-- | Finalize the AEAD context and return the authentication tag
aeadFinalize :: AEAD cipher -> Int -> AuthTag
-- | Simple AEAD encryption
aeadSimpleEncrypt :: (ByteArrayAccess aad, ByteArray ba) => AEAD a -> aad -> ba -> Int -> (AuthTag, ba)
-- | Simple AEAD decryption
aeadSimpleDecrypt :: (ByteArrayAccess aad, ByteArray ba) => AEAD a -> aad -> ba -> AuthTag -> Maybe ba
-- | an IV parametrized by the cipher
data IV c
-- | Create an IV for a specified block cipher
makeIV :: (ByteArrayAccess b, BlockCipher c) => b -> Maybe (IV c)
-- | Create an IV that is effectively representing the number 0
nullIV :: BlockCipher c => IV c
-- | Increment an IV by a number.
--
-- Assume the IV is in Big Endian format.
ivAdd :: IV c -> Int -> IV c
-- | Authentication Tag for AE cipher mode
newtype AuthTag
AuthTag :: Bytes -> AuthTag
[unAuthTag] :: AuthTag -> Bytes
-- | Provide the hash function construction method from block cipher
-- https://en.wikipedia.org/wiki/One-way_compression_function
module Crypto.ConstructHash.MiyaguchiPreneel
-- | Compute Miyaguchi-Preneel one way compress using the inferred block
-- cipher. Only safe when KEY-SIZE equals to BLOCK-SIZE.
--
-- Simple usage mp' msg :: MiyaguchiPreneel AES128
compute :: (ByteArrayAccess bin, BlockCipher cipher) => bin -> MiyaguchiPreneel cipher
-- | Compute Miyaguchi-Preneel one way compress using the supplied block
-- cipher.
compute' :: (ByteArrayAccess bin, BlockCipher cipher) => (Bytes -> cipher) -> bin -> MiyaguchiPreneel cipher
data MiyaguchiPreneel a
instance Data.ByteArray.Types.ByteArrayAccess (Crypto.ConstructHash.MiyaguchiPreneel.MiyaguchiPreneel a)
instance GHC.Classes.Eq (Crypto.ConstructHash.MiyaguchiPreneel.MiyaguchiPreneel a)
module Crypto.Cipher.Utils
validateKeySize :: (ByteArrayAccess key, Cipher cipher) => cipher -> key -> CryptoFailable key
module Crypto.Cipher.TripleDES
-- | 3DES with 3 different keys used all in the same direction
data DES_EEE3
-- | 3DES with 3 different keys used in alternative direction
data DES_EDE3
-- | 3DES where the first and third keys are equal, used in the same
-- direction
data DES_EEE2
-- | 3DES where the first and third keys are equal, used in alternative
-- direction
data DES_EDE2
instance GHC.Classes.Eq Crypto.Cipher.TripleDES.DES_EDE2
instance GHC.Classes.Eq Crypto.Cipher.TripleDES.DES_EEE2
instance GHC.Classes.Eq Crypto.Cipher.TripleDES.DES_EDE3
instance GHC.Classes.Eq Crypto.Cipher.TripleDES.DES_EEE3
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.TripleDES.DES_EDE2
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.TripleDES.DES_EDE2
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.TripleDES.DES_EEE2
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.TripleDES.DES_EEE2
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.TripleDES.DES_EDE3
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.TripleDES.DES_EDE3
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.TripleDES.DES_EEE3
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.TripleDES.DES_EEE3
module Crypto.Cipher.DES
-- | DES Context
data DES
instance GHC.Classes.Eq Crypto.Cipher.DES.DES
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.DES.DES
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.DES.DES
module Crypto.Cipher.Salsa
-- | Initialize a new Salsa context with the number of rounds, the key and
-- the nonce associated.
initialize :: (ByteArrayAccess key, ByteArrayAccess nonce) => Int -> key -> nonce -> State
-- | Combine the salsa output and an arbitrary message with a xor, and
-- return the combined output and the new state.
combine :: ByteArray ba => State -> ba -> (ba, State)
-- | Generate a number of bytes from the Salsa output directly
generate :: ByteArray ba => State -> Int -> (ba, State)
-- | Salsa context
newtype State
State :: ScrubbedBytes -> State
instance Control.DeepSeq.NFData Crypto.Cipher.Salsa.State
-- | Implementation of XSalsa20 algorithm
-- https://cr.yp.to/snuffle/xsalsa-20081128.pdf Based on the
-- Salsa20 algorithm with 256 bit key extended with 192 bit nonce
module Crypto.Cipher.XSalsa
-- | Initialize a new XSalsa context with the number of rounds, the key and
-- the nonce associated.
initialize :: (ByteArrayAccess key, ByteArrayAccess nonce) => Int -> key -> nonce -> State
-- | Use an already initialized context and new nonce material to derive
-- another XSalsa context.
--
-- This allows a multi-level cascade where a first key k1 and
-- nonce n1 is used to get HState(k1,n1), and this
-- value is then used as key k2 to build XSalsa(k2,n2).
-- Function initialize is to be called with the first 192 bits of
-- n1|n2, and the call to derive should add the
-- remaining 128 bits.
--
-- The output context always uses the same number of rounds as the input
-- context.
derive :: ByteArrayAccess nonce => State -> nonce -> State
-- | Combine the salsa output and an arbitrary message with a xor, and
-- return the combined output and the new state.
combine :: ByteArray ba => State -> ba -> (ba, State)
-- | Generate a number of bytes from the Salsa output directly
generate :: ByteArray ba => State -> Int -> (ba, State)
-- | Salsa context
data State
-- | Simple implementation of the RC4 stream cipher.
-- http://en.wikipedia.org/wiki/RC4
--
-- Initial FFI implementation by Peter White peter@janrain.com
--
-- Reorganized and simplified to have an opaque context.
module Crypto.Cipher.RC4
-- | RC4 context initialization.
--
-- seed the context with an initial key. the key size need to be adequate
-- otherwise security takes a hit.
initialize :: ByteArrayAccess key => key -> State
-- | RC4 xor combination of the rc4 stream with an input
combine :: ByteArray ba => State -> ba -> (State, ba)
-- | generate the next len bytes of the rc4 stream without combining it to
-- anything.
generate :: ByteArray ba => State -> Int -> (State, ba)
-- | The encryption state for RC4
data State
instance Control.DeepSeq.NFData Crypto.Cipher.RC4.State
instance Data.ByteArray.Types.ByteArrayAccess Crypto.Cipher.RC4.State
module Crypto.Cipher.ChaCha
-- | Initialize a new ChaCha context with the number of rounds, the key and
-- the nonce associated.
initialize :: (ByteArrayAccess key, ByteArrayAccess nonce) => Int -> key -> nonce -> State
-- | Combine the chacha output and an arbitrary message with a xor, and
-- return the combined output and the new state.
combine :: ByteArray ba => State -> ba -> (ba, State)
-- | Generate a number of bytes from the ChaCha output directly
generate :: ByteArray ba => State -> Int -> (ba, State)
-- | ChaCha context
data State
-- | Initialize simple ChaCha State
--
-- The seed need to be at least 40 bytes long
initializeSimple :: ByteArrayAccess seed => seed -> StateSimple
-- | similar to generate but assume certains values
generateSimple :: ByteArray ba => StateSimple -> Int -> (ba, StateSimple)
-- | ChaCha context for DRG purpose (see Crypto.Random.ChaChaDRG)
data StateSimple
instance Control.DeepSeq.NFData Crypto.Cipher.ChaCha.StateSimple
instance Control.DeepSeq.NFData Crypto.Cipher.ChaCha.State
module Crypto.Cipher.AES
-- | AES with 128 bit key
data AES128
-- | AES with 192 bit key
data AES192
-- | AES with 256 bit key
data AES256
instance Control.DeepSeq.NFData Crypto.Cipher.AES.AES256
instance Control.DeepSeq.NFData Crypto.Cipher.AES.AES192
instance Control.DeepSeq.NFData Crypto.Cipher.AES.AES128
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.AES.AES256
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.AES.AES256
instance Crypto.Cipher.Types.Block.BlockCipher128 Crypto.Cipher.AES.AES256
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.AES.AES192
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.AES.AES192
instance Crypto.Cipher.Types.Block.BlockCipher128 Crypto.Cipher.AES.AES192
instance Crypto.Cipher.Types.Base.Cipher Crypto.Cipher.AES.AES128
instance Crypto.Cipher.Types.Block.BlockCipher Crypto.Cipher.AES.AES128
instance Crypto.Cipher.Types.Block.BlockCipher128 Crypto.Cipher.AES.AES128
-- | Definitions of known hash algorithms
module Crypto.Hash.Algorithms
-- | Class representing hashing algorithms.
--
-- The interface presented here is update in place and lowlevel. the Hash
-- module takes care of hidding the mutable interface properly.
class HashAlgorithm a
-- | Blake2s (160 bits) cryptographic hash algorithm
data Blake2s_160
Blake2s_160 :: Blake2s_160
-- | Blake2s (224 bits) cryptographic hash algorithm
data Blake2s_224
Blake2s_224 :: Blake2s_224
-- | Blake2s (256 bits) cryptographic hash algorithm
data Blake2s_256
Blake2s_256 :: Blake2s_256
-- | Blake2sp (224 bits) cryptographic hash algorithm
data Blake2sp_224
Blake2sp_224 :: Blake2sp_224
-- | Blake2sp (256 bits) cryptographic hash algorithm
data Blake2sp_256
Blake2sp_256 :: Blake2sp_256
-- | Blake2b (160 bits) cryptographic hash algorithm
data Blake2b_160
Blake2b_160 :: Blake2b_160
-- | Blake2b (224 bits) cryptographic hash algorithm
data Blake2b_224
Blake2b_224 :: Blake2b_224
-- | Blake2b (256 bits) cryptographic hash algorithm
data Blake2b_256
Blake2b_256 :: Blake2b_256
-- | Blake2b (384 bits) cryptographic hash algorithm
data Blake2b_384
Blake2b_384 :: Blake2b_384
-- | Blake2b (512 bits) cryptographic hash algorithm
data Blake2b_512
Blake2b_512 :: Blake2b_512
-- | Blake2bp (512 bits) cryptographic hash algorithm
data Blake2bp_512
Blake2bp_512 :: Blake2bp_512
-- | MD2 cryptographic hash algorithm
data MD2
MD2 :: MD2
-- | MD4 cryptographic hash algorithm
data MD4
MD4 :: MD4
-- | MD5 cryptographic hash algorithm
data MD5
MD5 :: MD5
-- | SHA1 cryptographic hash algorithm
data SHA1
SHA1 :: SHA1
-- | SHA224 cryptographic hash algorithm
data SHA224
SHA224 :: SHA224
-- | SHA256 cryptographic hash algorithm
data SHA256
SHA256 :: SHA256
-- | SHA384 cryptographic hash algorithm
data SHA384
SHA384 :: SHA384
-- | SHA512 cryptographic hash algorithm
data SHA512
SHA512 :: SHA512
-- | SHA512t (224 bits) cryptographic hash algorithm
data SHA512t_224
SHA512t_224 :: SHA512t_224
-- | SHA512t (256 bits) cryptographic hash algorithm
data SHA512t_256
SHA512t_256 :: SHA512t_256
-- | RIPEMD160 cryptographic hash algorithm
data RIPEMD160
RIPEMD160 :: RIPEMD160
-- | Tiger cryptographic hash algorithm
data Tiger
Tiger :: Tiger
-- | Keccak (224 bits) cryptographic hash algorithm
data Keccak_224
Keccak_224 :: Keccak_224
-- | Keccak (256 bits) cryptographic hash algorithm
data Keccak_256
Keccak_256 :: Keccak_256
-- | Keccak (384 bits) cryptographic hash algorithm
data Keccak_384
Keccak_384 :: Keccak_384
-- | Keccak (512 bits) cryptographic hash algorithm
data Keccak_512
Keccak_512 :: Keccak_512
-- | SHA3 (224 bits) cryptographic hash algorithm
data SHA3_224
SHA3_224 :: SHA3_224
-- | SHA3 (256 bits) cryptographic hash algorithm
data SHA3_256
SHA3_256 :: SHA3_256
-- | SHA3 (384 bits) cryptographic hash algorithm
data SHA3_384
SHA3_384 :: SHA3_384
-- | SHA3 (512 bits) cryptographic hash algorithm
data SHA3_512
SHA3_512 :: SHA3_512
-- | SHAKE128 (128 bits) extendable output function. Supports an arbitrary
-- digest size, to be specified as a type parameter of kind Nat.
--
-- Note: outputs from SHAKE128 n and SHAKE128
-- m for the same input are correlated (one being a prefix of the
-- other). Results are unrelated to SHAKE256 results.
data SHAKE128 (bitlen :: Nat)
SHAKE128 :: SHAKE128
-- | SHAKE256 (256 bits) extendable output function. Supports an arbitrary
-- digest size, to be specified as a type parameter of kind Nat.
--
-- Note: outputs from SHAKE256 n and SHAKE256
-- m for the same input are correlated (one being a prefix of the
-- other). Results are unrelated to SHAKE128 results.
data SHAKE256 (bitlen :: Nat)
SHAKE256 :: SHAKE256
-- | Fast cryptographic hash.
--
-- It is especially known to target 64bits architectures.
--
-- Known supported digest sizes:
--
--
-- - Blake2b 160
-- - Blake2b 224
-- - Blake2b 256
-- - Blake2b 384
-- - Blake2b 512
--
data Blake2b (bitlen :: Nat)
Blake2b :: Blake2b
data Blake2bp (bitlen :: Nat)
Blake2bp :: Blake2bp
-- | Fast and secure alternative to SHA1 and HMAC-SHA1
--
-- It is espacially known to target 32bits architectures.
--
-- Known supported digest sizes:
--
--
-- - Blake2s 160
-- - Blake2s 224
-- - Blake2s 256
--
data Blake2s (bitlen :: Nat)
Blake2s :: Blake2s
data Blake2sp (bitlen :: Nat)
Blake2sp :: Blake2sp
-- | Skein256 (224 bits) cryptographic hash algorithm
data Skein256_224
Skein256_224 :: Skein256_224
-- | Skein256 (256 bits) cryptographic hash algorithm
data Skein256_256
Skein256_256 :: Skein256_256
-- | Skein512 (224 bits) cryptographic hash algorithm
data Skein512_224
Skein512_224 :: Skein512_224
-- | Skein512 (256 bits) cryptographic hash algorithm
data Skein512_256
Skein512_256 :: Skein512_256
-- | Skein512 (384 bits) cryptographic hash algorithm
data Skein512_384
Skein512_384 :: Skein512_384
-- | Skein512 (512 bits) cryptographic hash algorithm
data Skein512_512
Skein512_512 :: Skein512_512
-- | Whirlpool cryptographic hash algorithm
data Whirlpool
Whirlpool :: Whirlpool
-- | Generalized cryptographic hash interface, that you can use with
-- cryptographic hash algorithm that belong to the HashAlgorithm type
-- class.
--
--
-- 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.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
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.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
-- | 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
-- | 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
-- | Port of the bcrypt_pbkdf key derivation function from OpenBSD as
-- described at http://man.openbsd.org/bcrypt_pbkdf.3.
module Crypto.KDF.BCryptPBKDF
data Parameters
Parameters :: Int -> Int -> Parameters
-- | The number of user-defined iterations for the algorithm (must be >
-- 0)
[iterCounts] :: Parameters -> Int
-- | The number of bytes to generate out of BCryptPBKDF (must be in
-- 1..1024)
[outputLength] :: Parameters -> Int
-- | Derive a key of specified length using the bcrypt_pbkdf algorithm.
generate :: (ByteArray pass, ByteArray salt, ByteArray output) => Parameters -> pass -> salt -> output
-- | Internal hash function used by generate.
--
-- Normal users should not need this.
hashInternal :: (ByteArrayAccess pass, ByteArrayAccess salt, ByteArray output) => pass -> salt -> output
instance GHC.Show.Show Crypto.KDF.BCryptPBKDF.Parameters
instance GHC.Classes.Ord Crypto.KDF.BCryptPBKDF.Parameters
instance GHC.Classes.Eq Crypto.KDF.BCryptPBKDF.Parameters
-- | 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. No Show instance is provided, to
-- avoid printing by mistake.
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)
-- | Provide the KMAC (Keccak Message Authentication Code) algorithm,
-- derived from the SHA-3 base algorithm Keccak and defined in NIST
-- SP800-185.
module Crypto.MAC.KMAC
-- | Type class of SHAKE algorithms.
class HashAlgorithm a => HashSHAKE a
-- | Compute a KMAC using the supplied customization string and key.
kmac :: (HashSHAKE a, ByteArrayAccess string, ByteArrayAccess key, ByteArrayAccess ba) => string -> key -> ba -> KMAC a
-- | Represent a KMAC that is a phantom type with the hash used to produce
-- the mac.
--
-- The Eq instance is constant time. No Show instance is provided, to
-- avoid printing by mistake.
newtype KMAC a
KMAC :: Digest a -> KMAC a
[kmacGetDigest] :: KMAC a -> Digest a
-- | Represent an ongoing KMAC state, that can be appended with
-- update and finalized to a KMAC with finalize.
data Context a
-- | Initialize a new incremental KMAC context with the supplied
-- customization string and key.
initialize :: forall a string key. (HashSHAKE a, ByteArrayAccess string, ByteArrayAccess key) => string -> key -> Context a
-- | Incrementally update a KMAC context.
update :: (HashSHAKE a, ByteArrayAccess ba) => Context a -> ba -> Context a
-- | Incrementally update a KMAC context with multiple inputs.
updates :: (HashSHAKE a, ByteArrayAccess ba) => Context a -> [ba] -> Context a
-- | Finalize a KMAC context and return the KMAC.
finalize :: forall a. HashSHAKE a => Context a -> KMAC a
instance Data.ByteArray.Types.ByteArrayAccess (Crypto.MAC.KMAC.KMAC a)
instance GHC.Classes.Eq (Crypto.MAC.KMAC.KMAC 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
-- | Express an integer as an odd number and a power of 2
asPowerOf2AndOdd :: Integer -> (Int, Integer)
-- | 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
-- | Exponentiation in F₂m by computing a^b mod fx.
--
-- This implements an exponentiation by squaring based solution. It
-- inherits the same restrictions as squareF2m. Negative exponents
-- are disallowed.
powF2m :: BinaryPolynomial -> Integer -> 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
-- | Square rooot in F₂m.
--
-- We exploit the fact that a^(2^m) = a, or in particular,
-- a^(2^m - 1) = 1 from a classical result by Lagrange. Thus the
-- square root is simply a^(2^(m - 1)).
sqrtF2m :: 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^exponent 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.
--
-- Before GHC 8.4.2, powModSecInteger is missing from integer-gmp, so
-- expSafe has the same security as expFast.
expSafe :: Integer -> Integer -> Integer -> Integer
-- | Compute the modular exponentiation of base^exponent using the fastest
-- algorithm without any consideration for hiding parameters.
--
-- Use this function when all the parameters are public, otherwise
-- expSafe should be preferred.
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
-- | 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
-- | Computes the Jacobi symbol (a/n). 0 ≤ a < n; n ≥ 3 and odd.
--
-- The Legendre and Jacobi symbols are indistinguishable exactly when the
-- lower argument is an odd prime, in which case they have the same
-- value.
--
-- See algorithm 2.149 in "Handbook of Applied Cryptography" by Alfred J.
-- Menezes et al.
jacobi :: Integer -> Integer -> Maybe Integer
-- | Modular square root of g modulo a prime p.
--
-- If the modulus is found not to be prime, the function will raise a
-- ModulusAssertionError.
--
-- This implementation is variable time and should be used with public
-- parameters only.
squareRoot :: Integer -> Integer -> Maybe Integer
instance GHC.Show.Show Crypto.Number.ModArithmetic.ModulusAssertionError
instance GHC.Show.Show Crypto.Number.ModArithmetic.CoprimesAssertionError
instance GHC.Exception.Type.Exception Crypto.Number.ModArithmetic.ModulusAssertionError
instance GHC.Exception.Type.Exception Crypto.Number.ModArithmetic.CoprimesAssertionError
-- | Numbers at type level.
--
-- This module provides extensions to GHC.TypeLits and
-- GHC.TypeNats useful to work with cryptographic algorithms
-- parameterized with a variable bit length. Constraints like
-- IsDivisibleBy8 n ensure that the type-level parameter
-- is applicable to the algorithm.
--
-- Functions are also provided to test whether constraints are satisfied
-- from values known at runtime. The following example shows how to
-- discharge IsDivisibleBy8 in a computation fn requiring
-- this constraint:
--
--
-- withDivisibleBy8 :: Integer
-- -> (forall proxy n . (KnownNat n, IsDivisibleBy8 n) => proxy n -> a)
-- -> Maybe a
-- withDivisibleBy8 len fn = do
-- SomeNat p <- someNatVal len
-- Refl <- isDivisibleBy8 p
-- pure (fn p)
--
--
-- Function withDivisibleBy8 above returns Nothing when
-- the argument len is negative or not divisible by 8.
module Crypto.Number.Nat
-- | ensure the given bitlen is divisible by 8
type IsDivisibleBy8 bitLen = IsDiv8 bitLen bitLen ~ 'True
-- | ensure the given bitlen is lesser or equal to n
type IsAtMost (bitlen :: Nat) (n :: Nat) = IsLE bitlen n (bitlen <=? n) ~ 'True
-- | ensure the given bitlen is greater or equal to n
type IsAtLeast (bitlen :: Nat) (n :: Nat) = IsGE bitlen n (n <=? bitlen) ~ 'True
-- | get a runtime proof that the constraint IsDivisibleBy8
-- n is satified
isDivisibleBy8 :: KnownNat n => proxy n -> Maybe (IsDiv8 n n :~: 'True)
-- | get a runtime proof that the constraint IsAtMost value
-- bound is satified
isAtMost :: (KnownNat value, KnownNat bound) => proxy value -> proxy' bound -> Maybe ((value <=? bound) :~: 'True)
-- | get a runtime proof that the constraint IsAtLeast value
-- bound is satified
isAtLeast :: (KnownNat value, KnownNat bound) => proxy value -> proxy' bound -> Maybe ((bound <=? value) :~: 'True)
-- | 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
-- | Fast serialization primitives for integer using raw pointers (little
-- endian)
module Crypto.Number.Serialize.Internal.LE
-- | Fill a pointer with the little 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 little 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 (little endian)
module Crypto.Number.Serialize.LE
-- | i2osp converts a positive integer into a byte string.
--
-- The first byte is LSB (least significant byte); the last byte is the
-- MSB (most 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 exponent 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 exponent 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 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.
--
-- Note that the Arbitrary instance provided by QuickCheck for
-- Word64 does not have a uniform distribution. It is often better
-- to use instead arbitraryBoundedRandom.
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 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
-- | Check if a Point is the point at infinity
pointIsAtInfinity :: Point -> Bool
-- | Lift to curve a scalar
--
-- Using the curve generator as base point compute:
--
--
-- scalar * G
--
toPoint :: Scalar -> Point
-- | Return the x coordinate as a Scalar if the point is not at
-- infinity
pointX :: Point -> Maybe Scalar
-- | 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
-- | The scalar representing the curve order
scalarN :: 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
-- | Perform multiplication between two scalars
--
--
-- a * b
--
scalarMul :: Scalar -> Scalar -> Scalar
-- | Give the inverse of the scalar
--
--
-- 1 / a
--
--
-- warning: variable time
scalarInv :: Scalar -> Scalar
-- | Give the inverse of the scalar using safe exponentiation
--
--
-- 1 / a
--
scalarInvSafe :: 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 otherPassword :: 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:
--
--
-- - arithmetic functions for point addition, doubling, negation,
-- scalar multiplication with an arbitrary point, with the base point,
-- etc.
-- - arithmetic functions dealing with scalars modulo the prime order L
-- of the base point
--
--
-- All functions run in constant time unless noted otherwise.
--
-- Warnings:
--
--
-- - Curve edwards25519 has a cofactor h = 8 so the base point does not
-- generate the entire curve and points with order 2, 4, 8 exist. When
-- implementing cryptographic algorithms, special care must be taken
-- using one of the following methods:
- points must be checked for
-- membership in the prime-order subgroup
- or cofactor must be
-- cleared by multiplying points by 8
Utility functions are
-- provided to implement this. Testing subgroup membership with
-- pointHasPrimeOrder is 50-time slower than call
-- pointMulByCofactor.
-- - Scalar arithmetic is always reduced modulo L, allowing fixed
-- length and constant execution time, but this reduction is valid only
-- when points are in the prime-order subgroup.
-- - Because of modular reduction in this implementation it is not
-- possible to multiply points directly by scalars like 8.s or L. This
-- has to be decomposed into several steps.
--
module Crypto.ECC.Edwards25519
-- | A scalar modulo prime order of curve edwards25519.
data Scalar
-- | A point on curve edwards25519.
data Point
-- | Generate a random scalar.
scalarGenerate :: MonadRandom randomly => randomly Scalar
-- | Deserialize a little-endian number as a scalar. Input array can have
-- any length from 0 to 64 bytes.
--
-- Note: it is not advised to put secret information in the 3 lowest bits
-- of a scalar if this scalar may be multiplied to untrusted points
-- outside the prime-order subgroup.
scalarDecodeLong :: ByteArrayAccess bs => bs -> CryptoFailable Scalar
-- | Serialize a scalar to binary, i.e. a 32-byte little-endian number.
scalarEncode :: ByteArray bs => Scalar -> bs
-- | Deserialize a 32-byte array as a point, ensuring the point is valid on
-- edwards25519.
--
-- WARNING: variable time
pointDecode :: ByteArrayAccess bs => bs -> CryptoFailable Point
-- | Serialize a point to a 32-byte array.
--
-- Format is binary compatible with PublicKey from module
-- Crypto.PubKey.Ed25519.
pointEncode :: ByteArray bs => Point -> bs
-- | Test whether a point belongs to the prime-order subgroup generated by
-- the base point. Result is True for the identity point.
--
--
-- 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
-- | Implementation of AES-GCM-SIV, an AEAD scheme with nonce misuse
-- resistance defined in RFC 8452.
--
-- To achieve the nonce misuse-resistance property, encryption requires
-- two passes on the plaintext, hence no streaming API is provided. This
-- AEAD operates on complete inputs held in memory. For simplicity, the
-- implementation of decryption uses a similar pattern, with performance
-- penalty compared to an implementation which is able to merge both
-- passes.
--
-- The specification allows inputs up to 2^36 bytes but this
-- implementation requires AAD and plaintext/ciphertext to be both
-- smaller than 2^32 bytes.
module Crypto.Cipher.AESGCMSIV
-- | Nonce value for AES-GCM-SIV, always 12 bytes.
data Nonce
-- | Nonce smart constructor. Accepts only 12-byte inputs.
nonce :: ByteArrayAccess iv => iv -> CryptoFailable Nonce
-- | Generate a random nonce for use with AES-GCM-SIV.
generateNonce :: MonadRandom m => m Nonce
-- | AEAD encryption with the specified key and nonce. The key must be
-- given as an initialized AES128 or AES256 cipher.
--
-- Lengths of additional data and plaintext must be less than 2^32 bytes,
-- otherwise an exception is thrown.
encrypt :: (BlockCipher128 aes, ByteArrayAccess aad, ByteArray ba) => aes -> Nonce -> aad -> ba -> (AuthTag, ba)
-- | AEAD decryption with the specified key and nonce. The key must be
-- given as an initialized AES128 or AES256 cipher.
--
-- Lengths of additional data and ciphertext must be less than 2^32
-- bytes, otherwise an exception is thrown.
decrypt :: (BlockCipher128 aes, ByteArrayAccess aad, ByteArray ba) => aes -> Nonce -> aad -> ba -> AuthTag -> Maybe ba
instance Data.ByteArray.Types.ByteArrayAccess Crypto.Cipher.AESGCMSIV.Nonce
instance GHC.Classes.Eq Crypto.Cipher.AESGCMSIV.Nonce
instance GHC.Show.Show Crypto.Cipher.AESGCMSIV.Nonce
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:
--
--
-- - x is not out of range
-- - y is not out of range
-- - the equation y^2 = x^3 + a*x + b (mod p) holds
--
isPointValid :: Curve -> Point -> Bool
-- | WARNING: Signature operations may leak the private key.
-- Signature verification should be safe.
module Crypto.PubKey.ECC.ECDSA
-- | Represent a ECDSA signature namely R and S.
data Signature
Signature :: Integer -> Integer -> Signature
-- | ECDSA r
[sign_r] :: Signature -> Integer
-- | ECDSA s
[sign_s] :: Signature -> Integer
-- | ECC Public Point
type PublicPoint = Point
-- | ECDSA Public Key.
data PublicKey
PublicKey :: Curve -> PublicPoint -> PublicKey
[public_curve] :: PublicKey -> Curve
[public_q] :: PublicKey -> PublicPoint
-- | ECC Private Number
type PrivateNumber = Integer
-- | ECDSA Private Key.
data PrivateKey
PrivateKey :: Curve -> PrivateNumber -> PrivateKey
[private_curve] :: PrivateKey -> Curve
[private_d] :: PrivateKey -> PrivateNumber
-- | ECDSA Key Pair.
data KeyPair
KeyPair :: Curve -> PublicPoint -> PrivateNumber -> KeyPair
-- | Public key of a ECDSA Key pair.
toPublicKey :: KeyPair -> PublicKey
-- | Private key of a ECDSA Key pair.
toPrivateKey :: KeyPair -> PrivateKey
-- | Sign message using the private key and an explicit k number.
--
-- WARNING: Vulnerable to timing attacks.
signWith :: (ByteArrayAccess msg, HashAlgorithm hash) => Integer -> PrivateKey -> hash -> msg -> Maybe Signature
-- | Sign digest using the private key and an explicit k number.
--
-- WARNING: Vulnerable to timing attacks.
signDigestWith :: HashAlgorithm hash => Integer -> PrivateKey -> Digest hash -> Maybe Signature
-- | Sign message using the private key.
--
-- WARNING: Vulnerable to timing attacks.
sign :: (ByteArrayAccess msg, HashAlgorithm hash, MonadRandom m) => PrivateKey -> hash -> msg -> m Signature
-- | Sign digest using the private key.
--
-- WARNING: Vulnerable to timing attacks.
signDigest :: (HashAlgorithm hash, MonadRandom m) => PrivateKey -> Digest hash -> m Signature
-- | Verify a bytestring using the public key.
verify :: (ByteArrayAccess msg, HashAlgorithm hash) => hash -> PublicKey -> Signature -> msg -> Bool
-- | Verify a digest using the public key.
verifyDigest :: HashAlgorithm hash => PublicKey -> Signature -> Digest hash -> Bool
instance Data.Data.Data Crypto.PubKey.ECC.ECDSA.KeyPair
instance GHC.Classes.Eq Crypto.PubKey.ECC.ECDSA.KeyPair
instance GHC.Read.Read Crypto.PubKey.ECC.ECDSA.KeyPair
instance GHC.Show.Show Crypto.PubKey.ECC.ECDSA.KeyPair
instance Data.Data.Data Crypto.PubKey.ECC.ECDSA.PublicKey
instance GHC.Classes.Eq Crypto.PubKey.ECC.ECDSA.PublicKey
instance GHC.Read.Read Crypto.PubKey.ECC.ECDSA.PublicKey
instance GHC.Show.Show Crypto.PubKey.ECC.ECDSA.PublicKey
instance Data.Data.Data Crypto.PubKey.ECC.ECDSA.PrivateKey
instance GHC.Classes.Eq Crypto.PubKey.ECC.ECDSA.PrivateKey
instance GHC.Read.Read Crypto.PubKey.ECC.ECDSA.PrivateKey
instance GHC.Show.Show Crypto.PubKey.ECC.ECDSA.PrivateKey
instance Data.Data.Data Crypto.PubKey.ECC.ECDSA.Signature
instance GHC.Classes.Eq Crypto.PubKey.ECC.ECDSA.Signature
instance GHC.Read.Read Crypto.PubKey.ECC.ECDSA.Signature
instance GHC.Show.Show Crypto.PubKey.ECC.ECDSA.Signature
-- | Signature generation.
module Crypto.PubKey.ECC.Generate
-- | Generate Q given d.
--
-- WARNING: Vulnerable to timing attacks.
generateQ :: Curve -> Integer -> Point
-- | Generate a pair of (private, public) key.
--
-- WARNING: Vulnerable to timing attacks.
generate :: MonadRandom m => Curve -> m (PublicKey, PrivateKey)
-- | An implementation of the Digital Signature Algorithm (DSA)
module Crypto.PubKey.DSA
-- | Represent DSA parameters namely P, G, and Q.
data Params
Params :: Integer -> Integer -> Integer -> Params
-- | DSA p
[params_p] :: Params -> Integer
-- | DSA g
[params_g] :: Params -> Integer
-- | DSA q
[params_q] :: Params -> Integer
-- | Represent a DSA signature namely R and S.
data Signature
Signature :: Integer -> Integer -> Signature
-- | DSA r
[sign_r] :: Signature -> Integer
-- | DSA s
[sign_s] :: Signature -> Integer
-- | Represent a DSA public key.
data PublicKey
PublicKey :: Params -> PublicNumber -> PublicKey
-- | DSA parameters
[public_params] :: PublicKey -> Params
-- | DSA public Y
[public_y] :: PublicKey -> PublicNumber
-- | Represent a DSA private key.
--
-- Only x need to be secret. the DSA parameters are publicly shared with
-- the other side.
data PrivateKey
PrivateKey :: Params -> PrivateNumber -> PrivateKey
-- | DSA parameters
[private_params] :: PrivateKey -> Params
-- | DSA private X
[private_x] :: PrivateKey -> PrivateNumber
-- | DSA Public Number, usually embedded in DSA Public Key
type PublicNumber = Integer
-- | DSA Private Number, usually embedded in DSA Private Key
type PrivateNumber = Integer
-- | generate a private number with no specific property this number is
-- usually called X in DSA text.
generatePrivate :: MonadRandom m => Params -> m PrivateNumber
-- | Calculate the public number from the parameters and the private key
calculatePublic :: Params -> PrivateNumber -> PublicNumber
-- | sign message using the private key.
sign :: (ByteArrayAccess msg, HashAlgorithm hash, MonadRandom m) => PrivateKey -> hash -> msg -> m Signature
-- | sign message using the private key and an explicit k number.
signWith :: (ByteArrayAccess msg, HashAlgorithm hash) => Integer -> PrivateKey -> hash -> msg -> Maybe Signature
-- | verify a bytestring using the public key.
verify :: (ByteArrayAccess msg, HashAlgorithm hash) => hash -> PublicKey -> Signature -> msg -> Bool
-- | Represent a DSA key pair
data KeyPair
KeyPair :: Params -> PublicNumber -> PrivateNumber -> KeyPair
-- | Public key of a DSA Key pair
toPublicKey :: KeyPair -> PublicKey
-- | Private key of a DSA Key pair
toPrivateKey :: KeyPair -> PrivateKey
instance Data.Data.Data Crypto.PubKey.DSA.KeyPair
instance GHC.Classes.Eq Crypto.PubKey.DSA.KeyPair
instance GHC.Read.Read Crypto.PubKey.DSA.KeyPair
instance GHC.Show.Show Crypto.PubKey.DSA.KeyPair
instance Data.Data.Data Crypto.PubKey.DSA.PrivateKey
instance GHC.Classes.Eq Crypto.PubKey.DSA.PrivateKey
instance GHC.Read.Read Crypto.PubKey.DSA.PrivateKey
instance GHC.Show.Show Crypto.PubKey.DSA.PrivateKey
instance Data.Data.Data Crypto.PubKey.DSA.PublicKey
instance GHC.Classes.Eq Crypto.PubKey.DSA.PublicKey
instance GHC.Read.Read Crypto.PubKey.DSA.PublicKey
instance GHC.Show.Show Crypto.PubKey.DSA.PublicKey
instance Data.Data.Data Crypto.PubKey.DSA.Signature
instance GHC.Classes.Eq Crypto.PubKey.DSA.Signature
instance GHC.Read.Read Crypto.PubKey.DSA.Signature
instance GHC.Show.Show Crypto.PubKey.DSA.Signature
instance Data.Data.Data Crypto.PubKey.DSA.Params
instance GHC.Classes.Eq Crypto.PubKey.DSA.Params
instance GHC.Read.Read Crypto.PubKey.DSA.Params
instance GHC.Show.Show Crypto.PubKey.DSA.Params
instance Control.DeepSeq.NFData Crypto.PubKey.DSA.KeyPair
instance Control.DeepSeq.NFData Crypto.PubKey.DSA.PrivateKey
instance Control.DeepSeq.NFData Crypto.PubKey.DSA.PublicKey
instance Control.DeepSeq.NFData Crypto.PubKey.DSA.Signature
instance Control.DeepSeq.NFData Crypto.PubKey.DSA.Params
module Crypto.Number.Prime
-- | Generate a prime number of the required bitsize (i.e. in the range
-- [2^(b-1)+2^(b-2), 2^b)).
--
-- May throw a CryptoError_PrimeSizeInvalid if the requested size
-- is less than 5 bits, as the smallest prime meeting these conditions is
-- 29. This function requires that the two highest bits are set, so that
-- when multiplied with another prime to create a key, it is guaranteed
-- to be of the proper size.
generatePrime :: MonadRandom m => Int -> m Integer
-- | Generate a prime number of the form 2p+1 where p is also prime. it is
-- also knowed as a Sophie Germaine prime or safe prime.
--
-- The number of safe prime is significantly smaller to the number of
-- prime, as such it shouldn't be used if this number is supposed to be
-- kept safe.
--
-- May throw a CryptoError_PrimeSizeInvalid if the requested size
-- is less than 6 bits, as the smallest safe prime with the two highest
-- bits set is 59.
generateSafePrime :: MonadRandom m => Int -> m Integer
-- | Returns if the number is probably prime. First a list of small primes
-- are implicitely tested for divisibility, then a fermat primality test
-- is used with arbitrary numbers and then the Miller Rabin algorithm is
-- used with an accuracy of 30 recursions.
isProbablyPrime :: Integer -> Bool
-- | Find a prime from a starting point with no specific property.
findPrimeFrom :: Integer -> Integer
-- | Find a prime from a starting point where the property hold.
findPrimeFromWith :: (Integer -> Bool) -> Integer -> Integer
-- | Miller Rabin algorithm return if the number is probably prime or
-- composite. the tries parameter is the number of recursion, that
-- determines the accuracy of the test.
primalityTestMillerRabin :: Int -> Integer -> Bool
-- | Test naively is integer is prime. while naive, we skip even number and
-- stop iteration at i > sqrt(n)
primalityTestNaive :: Integer -> Bool
-- | Probabilitic Test using Fermat primility test. Beware of Carmichael
-- numbers that are Fermat liars, i.e. this test is useless for them.
-- always combines with some other test.
primalityTestFermat :: Int -> Integer -> Integer -> Bool
-- | Test is two integer are coprime to each other
isCoprime :: Integer -> Integer -> Bool
module Crypto.PubKey.Rabin.Types
-- | Error possible during encryption, decryption or signing.
data Error
-- | the message to encrypt is too long
MessageTooLong :: Error
-- | the message decrypted doesn't have a OAEP structure
MessageNotRecognized :: Error
-- | some parameters lead to breaking assumptions
InvalidParameters :: Error
-- | Generate primes p & q
generatePrimes :: MonadRandom m => Int -> PrimeCondition -> PrimeCondition -> m (Integer, Integer)
instance GHC.Classes.Eq Crypto.PubKey.Rabin.Types.Error
instance GHC.Show.Show Crypto.PubKey.Rabin.Types.Error
-- | OAEP padding scheme. See
-- http://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding.
module Crypto.PubKey.Rabin.OAEP
-- | Parameters for OAEP padding.
data OAEPParams hash seed output
OAEPParams :: hash -> MaskGenAlgorithm seed output -> Maybe ByteString -> OAEPParams hash seed output
-- | hash function to use
[oaepHash] :: OAEPParams hash seed output -> hash
-- | mask Gen algorithm to use
[oaepMaskGenAlg] :: OAEPParams hash seed output -> MaskGenAlgorithm seed output
-- | optional label prepended to message
[oaepLabel] :: OAEPParams hash seed output -> Maybe ByteString
-- | Default Params with a specified hash function.
defaultOAEPParams :: (ByteArrayAccess seed, ByteArray output, HashAlgorithm hash) => hash -> OAEPParams hash seed output
-- | Pad a message using OAEP.
pad :: HashAlgorithm hash => ByteString -> OAEPParams hash ByteString ByteString -> Int -> ByteString -> Either Error ByteString
-- | Un-pad a OAEP encoded message.
unpad :: HashAlgorithm hash => OAEPParams hash ByteString ByteString -> Int -> ByteString -> Either Error ByteString
-- | Rabin-Williams cryptosystem for public-key encryption and digital
-- signature. See pages 323 - 324 in "Computational Number Theory and
-- Modern Cryptography" by Song Y. Yan. Also inspired by
-- https://github.com/vanilala/vncrypt/blob/master/vncrypt/vnrw_gmp.c.
module Crypto.PubKey.Rabin.RW
-- | Represent a Rabin-Williams public key.
data PublicKey
PublicKey :: Int -> Integer -> PublicKey
-- | size of key in bytes
[public_size] :: PublicKey -> Int
-- | public p*q
[public_n] :: PublicKey -> Integer
-- | Represent a Rabin-Williams private key.
data PrivateKey
PrivateKey :: PublicKey -> Integer -> Integer -> Integer -> PrivateKey
[private_pub] :: PrivateKey -> PublicKey
-- | p prime number
[private_p] :: PrivateKey -> Integer
-- | q prime number
[private_q] :: PrivateKey -> Integer
[private_d] :: PrivateKey -> Integer
-- | Generate a pair of (private, public) key of size in bytes. Prime p is
-- congruent 3 mod 8 and prime q is congruent 7 mod 8.
generate :: MonadRandom m => Int -> m (PublicKey, PrivateKey)
-- | Encrypt plaintext using public key.
encrypt :: (HashAlgorithm hash, MonadRandom m) => OAEPParams hash ByteString ByteString -> PublicKey -> ByteString -> m (Either Error ByteString)
-- | Encrypt plaintext using public key an a predefined OAEP seed.
--
-- See algorithm 8.11 in "Handbook of Applied Cryptography" by Alfred J.
-- Menezes et al.
encryptWithSeed :: HashAlgorithm hash => ByteString -> OAEPParams hash ByteString ByteString -> PublicKey -> ByteString -> Either Error ByteString
-- | Decrypt ciphertext using private key.
decrypt :: HashAlgorithm hash => OAEPParams hash ByteString ByteString -> PrivateKey -> ByteString -> Maybe ByteString
-- | Sign message using hash algorithm and private key.
sign :: HashAlgorithm hash => PrivateKey -> hash -> ByteString -> Either Error Integer
-- | Verify signature using hash algorithm and public key.
verify :: HashAlgorithm hash => PublicKey -> hash -> ByteString -> Integer -> Bool
instance Data.Data.Data Crypto.PubKey.Rabin.RW.PrivateKey
instance GHC.Classes.Eq Crypto.PubKey.Rabin.RW.PrivateKey
instance GHC.Read.Read Crypto.PubKey.Rabin.RW.PrivateKey
instance GHC.Show.Show Crypto.PubKey.Rabin.RW.PrivateKey
instance Data.Data.Data Crypto.PubKey.Rabin.RW.PublicKey
instance GHC.Classes.Eq Crypto.PubKey.Rabin.RW.PublicKey
instance GHC.Read.Read Crypto.PubKey.Rabin.RW.PublicKey
instance GHC.Show.Show Crypto.PubKey.Rabin.RW.PublicKey
-- | Modified-Rabin public-key digital signature algorithm. See algorithm
-- 11.30 in "Handbook of Applied Cryptography" by Alfred J. Menezes et
-- al.
module Crypto.PubKey.Rabin.Modified
-- | Represent a Modified-Rabin public key.
data PublicKey
PublicKey :: Int -> Integer -> PublicKey
-- | size of key in bytes
[public_size] :: PublicKey -> Int
-- | public p*q
[public_n] :: PublicKey -> Integer
-- | Represent a Modified-Rabin private key.
data PrivateKey
PrivateKey :: PublicKey -> Integer -> Integer -> Integer -> PrivateKey
[private_pub] :: PrivateKey -> PublicKey
-- | p prime number
[private_p] :: PrivateKey -> Integer
-- | q prime number
[private_q] :: PrivateKey -> Integer
[private_d] :: PrivateKey -> Integer
-- | Generate a pair of (private, public) key of size in bytes. Prime p is
-- congruent 3 mod 8 and prime q is congruent 7 mod 8.
generate :: MonadRandom m => Int -> m (PublicKey, PrivateKey)
-- | Sign message using hash algorithm and private key.
sign :: HashAlgorithm hash => PrivateKey -> hash -> ByteString -> Either Error Integer
-- | Verify signature using hash algorithm and public key.
verify :: HashAlgorithm hash => PublicKey -> hash -> ByteString -> Integer -> Bool
instance Data.Data.Data Crypto.PubKey.Rabin.Modified.PrivateKey
instance GHC.Classes.Eq Crypto.PubKey.Rabin.Modified.PrivateKey
instance GHC.Read.Read Crypto.PubKey.Rabin.Modified.PrivateKey
instance GHC.Show.Show Crypto.PubKey.Rabin.Modified.PrivateKey
instance Data.Data.Data Crypto.PubKey.Rabin.Modified.PublicKey
instance GHC.Classes.Eq Crypto.PubKey.Rabin.Modified.PublicKey
instance GHC.Read.Read Crypto.PubKey.Rabin.Modified.PublicKey
instance GHC.Show.Show Crypto.PubKey.Rabin.Modified.PublicKey
-- | Rabin cryptosystem for public-key cryptography and digital signature.
module Crypto.PubKey.Rabin.Basic
-- | Represent a Rabin public key.
data PublicKey
PublicKey :: Int -> Integer -> PublicKey
-- | size of key in bytes
[public_size] :: PublicKey -> Int
-- | public p*q
[public_n] :: PublicKey -> Integer
-- | Represent a Rabin private key.
data PrivateKey
PrivateKey :: PublicKey -> Integer -> Integer -> Integer -> Integer -> PrivateKey
[private_pub] :: PrivateKey -> PublicKey
-- | p prime number
[private_p] :: PrivateKey -> Integer
-- | q prime number
[private_q] :: PrivateKey -> Integer
[private_a] :: PrivateKey -> Integer
[private_b] :: PrivateKey -> Integer
-- | Rabin Signature.
data Signature
Signature :: (Integer, Integer) -> Signature
-- | Generate a pair of (private, public) key of size in bytes. Primes p
-- and q are both congruent 3 mod 4.
--
-- See algorithm 8.11 in "Handbook of Applied Cryptography" by Alfred J.
-- Menezes et al.
generate :: MonadRandom m => Int -> m (PublicKey, PrivateKey)
-- | Encrypt plaintext using public key.
encrypt :: (HashAlgorithm hash, MonadRandom m) => OAEPParams hash ByteString ByteString -> PublicKey -> ByteString -> m (Either Error ByteString)
-- | Encrypt plaintext using public key an a predefined OAEP seed.
--
-- See algorithm 8.11 in "Handbook of Applied Cryptography" by Alfred J.
-- Menezes et al.
encryptWithSeed :: HashAlgorithm hash => ByteString -> OAEPParams hash ByteString ByteString -> PublicKey -> ByteString -> Either Error ByteString
-- | Decrypt ciphertext using private key.
--
-- See algorithm 8.12 in "Handbook of Applied Cryptography" by Alfred J.
-- Menezes et al.
decrypt :: HashAlgorithm hash => OAEPParams hash ByteString ByteString -> PrivateKey -> ByteString -> Maybe ByteString
-- | Sign message using hash algorithm and private key.
--
-- See https://en.wikipedia.org/wiki/Rabin_signature_algorithm.
sign :: (MonadRandom m, HashAlgorithm hash) => PrivateKey -> hash -> ByteString -> m (Either Error Signature)
-- | Sign message using padding, hash algorithm and private key.
--
-- See https://en.wikipedia.org/wiki/Rabin_signature_algorithm.
signWith :: HashAlgorithm hash => ByteString -> PrivateKey -> hash -> ByteString -> Either Error Signature
-- | Verify signature using hash algorithm and public key.
--
-- See https://en.wikipedia.org/wiki/Rabin_signature_algorithm.
verify :: HashAlgorithm hash => PublicKey -> hash -> ByteString -> Signature -> Bool
instance Data.Data.Data Crypto.PubKey.Rabin.Basic.Signature
instance GHC.Classes.Eq Crypto.PubKey.Rabin.Basic.Signature
instance GHC.Read.Read Crypto.PubKey.Rabin.Basic.Signature
instance GHC.Show.Show Crypto.PubKey.Rabin.Basic.Signature
instance Data.Data.Data Crypto.PubKey.Rabin.Basic.PrivateKey
instance GHC.Classes.Eq Crypto.PubKey.Rabin.Basic.PrivateKey
instance GHC.Read.Read Crypto.PubKey.Rabin.Basic.PrivateKey
instance GHC.Show.Show Crypto.PubKey.Rabin.Basic.PrivateKey
instance Data.Data.Data Crypto.PubKey.Rabin.Basic.PublicKey
instance GHC.Classes.Eq Crypto.PubKey.Rabin.Basic.PublicKey
instance GHC.Read.Read Crypto.PubKey.Rabin.Basic.PublicKey
instance GHC.Show.Show Crypto.PubKey.Rabin.Basic.PublicKey
module Crypto.PubKey.RSA
-- | 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
-- | 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 exponent 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 exponent 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
-- | Blinder which is used to obfuscate the timing of the decryption
-- primitive (used by decryption and signing).
data Blinder
Blinder :: !Integer -> !Integer -> Blinder
-- | Generate a key pair given p and q.
--
-- p and q need to be distinct prime numbers.
--
-- e need to be coprime to phi=(p-1)*(q-1). If that's not the case, the
-- function will not return a key pair. A small hamming weight results in
-- better performance.
--
--
-- - e=0x10001 is a popular choice
-- - e=3 is popular as well, but proven to not be as secure for some
-- cases.
--
generateWith :: (Integer, Integer) -> Int -> Integer -> Maybe (PublicKey, PrivateKey)
-- | generate a pair of (private, public) key of size in bytes.
generate :: MonadRandom m => Int -> Integer -> m (PublicKey, PrivateKey)
-- | Generate a blinder to use with decryption and signing operation
--
-- the unique parameter apart from the random number generator is the
-- public key value N.
generateBlinder :: MonadRandom m => Integer -> m Blinder
module Crypto.PubKey.RSA.PSS
-- | Parameters for PSS signature/verification.
data PSSParams hash seed output
PSSParams :: hash -> MaskGenAlgorithm seed output -> Int -> Word8 -> PSSParams hash seed output
-- | Hash function to use
[pssHash] :: PSSParams hash seed output -> hash
-- | Mask Gen algorithm to use
[pssMaskGenAlg] :: PSSParams hash seed output -> MaskGenAlgorithm seed output
-- | Length of salt. need to be <= to hLen.
[pssSaltLength] :: PSSParams hash seed output -> Int
-- | Trailer field, usually 0xbc
[pssTrailerField] :: PSSParams hash seed output -> Word8
-- | Default Params with a specified hash function
defaultPSSParams :: (ByteArrayAccess seed, ByteArray output, HashAlgorithm hash) => hash -> PSSParams hash seed output
-- | Default Params using SHA1 algorithm.
defaultPSSParamsSHA1 :: PSSParams SHA1 ByteString ByteString
-- | Sign using the PSS parameters and the salt explicitely passed as
-- parameters.
--
-- the function ignore SaltLength from the PSS Parameters
signWithSalt :: HashAlgorithm hash => ByteString -> Maybe Blinder -> PSSParams hash ByteString ByteString -> PrivateKey -> ByteString -> Either Error ByteString
-- | Sign using the PSS parameters and the salt explicitely passed as
-- parameters.
--
-- the function ignore SaltLength from the PSS Parameters
signDigestWithSalt :: HashAlgorithm hash => ByteString -> Maybe Blinder -> PSSParams hash ByteString ByteString -> PrivateKey -> Digest hash -> Either Error ByteString
-- | Sign using the PSS Parameters
sign :: (HashAlgorithm hash, MonadRandom m) => Maybe Blinder -> PSSParams hash ByteString ByteString -> PrivateKey -> ByteString -> m (Either Error ByteString)
-- | Sign using the PSS Parameters
signDigest :: (HashAlgorithm hash, MonadRandom m) => Maybe Blinder -> PSSParams hash ByteString ByteString -> PrivateKey -> Digest hash -> m (Either Error ByteString)
-- | Sign using the PSS Parameters and an automatically generated blinder.
signSafer :: (HashAlgorithm hash, MonadRandom m) => PSSParams hash ByteString ByteString -> PrivateKey -> ByteString -> m (Either Error ByteString)
-- | Sign using the PSS Parameters and an automatically generated blinder.
signDigestSafer :: (HashAlgorithm hash, MonadRandom m) => PSSParams hash ByteString ByteString -> PrivateKey -> Digest hash -> m (Either Error ByteString)
-- | Verify a signature using the PSS Parameters
verify :: HashAlgorithm hash => PSSParams hash ByteString ByteString -> PublicKey -> ByteString -> ByteString -> Bool
-- | Verify a signature using the PSS Parameters
verifyDigest :: HashAlgorithm hash => PSSParams hash ByteString ByteString -> PublicKey -> Digest hash -> ByteString -> Bool
module Crypto.PubKey.RSA.PKCS15
-- | This produce a standard PKCS1.5 padding for encryption
pad :: (MonadRandom m, ByteArray message) => Int -> message -> m (Either Error message)
-- | Produce a standard PKCS1.5 padding for signature
padSignature :: ByteArray signature => Int -> signature -> Either Error signature
-- | Try to remove a standard PKCS1.5 encryption padding.
unpad :: ByteArray bytearray => bytearray -> Either Error bytearray
-- | decrypt message using the private key.
--
-- When the decryption is not in a context where an attacker could gain
-- information from the timing of the operation, the blinder can be set
-- to None.
--
-- If unsure always set a blinder or use decryptSafer
--
-- The message is returned un-padded.
decrypt :: Maybe Blinder -> PrivateKey -> ByteString -> Either Error ByteString
-- | decrypt message using the private key and by automatically generating
-- a blinder.
decryptSafer :: MonadRandom m => PrivateKey -> ByteString -> m (Either Error ByteString)
-- | sign message using private key, a hash and its ASN1 description
--
-- When the signature is not in a context where an attacker could gain
-- information from the timing of the operation, the blinder can be set
-- to None.
--
-- If unsure always set a blinder or use signSafer
sign :: HashAlgorithmASN1 hashAlg => Maybe Blinder -> Maybe hashAlg -> PrivateKey -> ByteString -> Either Error ByteString
-- | sign message using the private key and by automatically generating a
-- blinder.
signSafer :: (HashAlgorithmASN1 hashAlg, MonadRandom m) => Maybe hashAlg -> PrivateKey -> ByteString -> m (Either Error ByteString)
-- | encrypt a bytestring using the public key.
--
-- The message needs to be smaller than the key size - 11. The message
-- should not be padded.
encrypt :: MonadRandom m => PublicKey -> ByteString -> m (Either Error ByteString)
-- | verify message with the signed message
verify :: HashAlgorithmASN1 hashAlg => Maybe hashAlg -> PublicKey -> ByteString -> ByteString -> Bool
-- | A specialized class for hash algorithm that can product a ASN1 wrapped
-- description the algorithm plus the content of the digest.
class HashAlgorithm hashAlg => HashAlgorithmASN1 hashAlg
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.MD2.MD2
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.MD5.MD5
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA1.SHA1
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA224.SHA224
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA256.SHA256
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA384.SHA384
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA512.SHA512
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA512t.SHA512t_224
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.SHA512t.SHA512t_256
instance Crypto.PubKey.RSA.PKCS15.HashAlgorithmASN1 Crypto.Hash.RIPEMD160.RIPEMD160
-- | RSA OAEP mode
-- http://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding
module Crypto.PubKey.RSA.OAEP
-- | Parameters for OAEP encryption/decryption
data OAEPParams hash seed output
OAEPParams :: hash -> MaskGenAlgorithm seed output -> Maybe ByteString -> OAEPParams hash seed output
-- | Hash function to use.
[oaepHash] :: OAEPParams hash seed output -> hash
-- | Mask Gen algorithm to use.
[oaepMaskGenAlg] :: OAEPParams hash seed output -> MaskGenAlgorithm seed output
-- | Optional label prepended to message.
[oaepLabel] :: OAEPParams hash seed output -> Maybe ByteString
-- | Default Params with a specified hash function
defaultOAEPParams :: (ByteArrayAccess seed, ByteArray output, HashAlgorithm hash) => hash -> OAEPParams hash seed output
-- | Encrypt a message using OAEP with a predefined seed.
encryptWithSeed :: HashAlgorithm hash => ByteString -> OAEPParams hash ByteString ByteString -> PublicKey -> ByteString -> Either Error ByteString
-- | Encrypt a message using OAEP
encrypt :: (HashAlgorithm hash, MonadRandom m) => OAEPParams hash ByteString ByteString -> PublicKey -> ByteString -> m (Either Error ByteString)
-- | Decrypt a ciphertext using OAEP
--
-- When the signature is not in a context where an attacker could gain
-- information from the timing of the operation, the blinder can be set
-- to None.
--
-- If unsure always set a blinder or use decryptSafer
decrypt :: HashAlgorithm hash => Maybe Blinder -> OAEPParams hash ByteString ByteString -> PrivateKey -> ByteString -> Either Error ByteString
-- | Decrypt a ciphertext using OAEP and by automatically generating a
-- blinder.
decryptSafer :: (HashAlgorithm hash, MonadRandom m) => OAEPParams hash ByteString ByteString -> PrivateKey -> ByteString -> m (Either Error ByteString)
module Crypto.PubKey.DH
-- | Represent Diffie Hellman parameters namely P (prime), and G
-- (generator).
data Params
Params :: Integer -> Integer -> Int -> Params
[params_p] :: Params -> Integer
[params_g] :: Params -> Integer
[params_bits] :: Params -> Int
-- | Represent Diffie Hellman public number Y.
newtype PublicNumber
PublicNumber :: Integer -> PublicNumber
-- | Represent Diffie Hellman private number X.
newtype PrivateNumber
PrivateNumber :: Integer -> PrivateNumber
-- | Represent Diffie Hellman shared secret.
newtype SharedKey
SharedKey :: ScrubbedBytes -> SharedKey
-- | generate params from a specific generator (2 or 5 are common values)
-- we generate a safe prime (a prime number of the form 2p+1 where p is
-- also prime)
generateParams :: MonadRandom m => Int -> Integer -> m Params
-- | generate a private number with no specific property this number is
-- usually called X in DH text.
generatePrivate :: MonadRandom m => Params -> m PrivateNumber
-- | calculate the public number from the parameters and the private key
-- this number is usually called Y in DH text.
calculatePublic :: Params -> PrivateNumber -> PublicNumber
-- | calculate the public number from the parameters and the private key
-- this number is usually called Y in DH text.
--
-- DEPRECATED use calculatePublic
generatePublic :: Params -> PrivateNumber -> PublicNumber
-- | generate a shared key using our private number and the other party
-- public number
getShared :: Params -> PrivateNumber -> PublicNumber -> SharedKey
instance Control.DeepSeq.NFData Crypto.PubKey.DH.SharedKey
instance Data.ByteArray.Types.ByteArrayAccess Crypto.PubKey.DH.SharedKey
instance GHC.Classes.Eq Crypto.PubKey.DH.SharedKey
instance GHC.Show.Show Crypto.PubKey.DH.SharedKey
instance Control.DeepSeq.NFData Crypto.PubKey.DH.PrivateNumber
instance GHC.Classes.Ord Crypto.PubKey.DH.PrivateNumber
instance GHC.Num.Num Crypto.PubKey.DH.PrivateNumber
instance GHC.Real.Real Crypto.PubKey.DH.PrivateNumber
instance GHC.Enum.Enum Crypto.PubKey.DH.PrivateNumber
instance GHC.Classes.Eq Crypto.PubKey.DH.PrivateNumber
instance GHC.Read.Read Crypto.PubKey.DH.PrivateNumber
instance GHC.Show.Show Crypto.PubKey.DH.PrivateNumber
instance Control.DeepSeq.NFData Crypto.PubKey.DH.PublicNumber
instance GHC.Classes.Ord Crypto.PubKey.DH.PublicNumber
instance GHC.Num.Num Crypto.PubKey.DH.PublicNumber
instance GHC.Real.Real Crypto.PubKey.DH.PublicNumber
instance GHC.Enum.Enum Crypto.PubKey.DH.PublicNumber
instance GHC.Classes.Eq Crypto.PubKey.DH.PublicNumber
instance GHC.Read.Read Crypto.PubKey.DH.PublicNumber
instance GHC.Show.Show Crypto.PubKey.DH.PublicNumber
instance Data.Data.Data Crypto.PubKey.DH.Params
instance GHC.Classes.Eq Crypto.PubKey.DH.Params
instance GHC.Read.Read Crypto.PubKey.DH.Params
instance GHC.Show.Show Crypto.PubKey.DH.Params
instance Control.DeepSeq.NFData Crypto.PubKey.DH.Params
-- | Elliptic curve Diffie Hellman
module Crypto.PubKey.ECC.DH
-- | Define either a binary curve or a prime curve.
data Curve
-- | ECC Public Point
type PublicPoint = Point
-- | ECC Private Number
type PrivateNumber = Integer
-- | Represent Diffie Hellman shared secret.
newtype SharedKey
SharedKey :: ScrubbedBytes -> SharedKey
-- | Generating a private number d.
generatePrivate :: MonadRandom m => Curve -> m PrivateNumber
-- | Generating a public point Q.
calculatePublic :: Curve -> PrivateNumber -> PublicPoint
-- | Generating a shared key using our private number and the other party
-- public point.
getShared :: Curve -> PrivateNumber -> PublicPoint -> SharedKey
-- | Elliptic Curve Cryptography
module Crypto.ECC
-- | P256 Curve
--
-- also known as P256
data Curve_P256R1
Curve_P256R1 :: Curve_P256R1
data Curve_P384R1
Curve_P384R1 :: Curve_P384R1
data Curve_P521R1
Curve_P521R1 :: Curve_P521R1
data Curve_X25519
Curve_X25519 :: Curve_X25519
data Curve_X448
Curve_X448 :: Curve_X448
data Curve_Edwards25519
Curve_Edwards25519 :: Curve_Edwards25519
class EllipticCurve curve where {
-- | Point on an Elliptic Curve
type family Point curve :: Type;
-- | Scalar in the Elliptic Curve domain
type family Scalar curve :: Type;
}
-- | Generate a new random scalar on the curve. The scalar will represent a
-- number between 1 and the order of the curve non included
curveGenerateScalar :: (EllipticCurve curve, MonadRandom randomly) => proxy curve -> randomly (Scalar curve)
-- | Generate a new random keypair
curveGenerateKeyPair :: (EllipticCurve curve, MonadRandom randomly) => proxy curve -> randomly (KeyPair curve)
-- | Get the curve size in bits
curveSizeBits :: EllipticCurve curve => proxy curve -> Int
-- | Encode a elliptic curve point into binary form
encodePoint :: (EllipticCurve curve, ByteArray bs) => proxy curve -> Point curve -> bs
-- | Try to decode the binary form of an elliptic curve point
decodePoint :: (EllipticCurve curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (Point curve)
class EllipticCurve curve => EllipticCurveDH curve
-- | Generate a Diffie hellman secret value.
--
-- This is generally just the .x coordinate of the resulting point, that
-- is not hashed.
--
-- use pointSmul to keep the result in Point format.
--
-- WARNING: Curve implementations may return a special value or an
-- exception when the public point lies in a subgroup of small order.
-- This function is adequate when the scalar is in expected range and
-- contributory behaviour is not needed. Otherwise use ecdh.
ecdhRaw :: EllipticCurveDH curve => proxy curve -> Scalar curve -> Point curve -> SharedSecret
-- | Generate a Diffie hellman secret value and verify that the result is
-- not the point at infinity.
--
-- This additional test avoids risks existing with function
-- ecdhRaw. Implementations always return a CryptoError
-- instead of a special value or an exception.
ecdh :: EllipticCurveDH curve => proxy curve -> Scalar curve -> Point curve -> CryptoFailable SharedSecret
class (EllipticCurve curve, Eq (Point curve)) => EllipticCurveArith curve
-- | Add points on a curve
pointAdd :: EllipticCurveArith curve => proxy curve -> Point curve -> Point curve -> Point curve
-- | Negate a curve point
pointNegate :: EllipticCurveArith curve => proxy curve -> Point curve -> Point curve
-- | Scalar Multiplication on a curve
pointSmul :: EllipticCurveArith curve => proxy curve -> Scalar curve -> Point curve -> Point curve
class (EllipticCurveArith curve, Eq (Scalar curve)) => EllipticCurveBasepointArith curve
-- | Get the curve order size in bits
curveOrderBits :: EllipticCurveBasepointArith curve => proxy curve -> Int
-- | Multiply a scalar with the curve base point
pointBaseSmul :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Point curve
-- | Multiply the point p with s2 and add a lifted to
-- curve value s1
pointsSmulVarTime :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Scalar curve -> Point curve -> Point curve
-- | Encode an elliptic curve scalar into big-endian form
encodeScalar :: (EllipticCurveBasepointArith curve, ByteArray bs) => proxy curve -> Scalar curve -> bs
-- | Try to decode the big-endian form of an elliptic curve scalar
decodeScalar :: (EllipticCurveBasepointArith curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (Scalar curve)
-- | Convert an elliptic curve scalar to an integer
scalarToInteger :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Integer
-- | Try to create an elliptic curve scalar from an integer
scalarFromInteger :: EllipticCurveBasepointArith curve => proxy curve -> Integer -> CryptoFailable (Scalar curve)
-- | Add two scalars and reduce modulo the curve order
scalarAdd :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Scalar curve -> Scalar curve
-- | Multiply two scalars and reduce modulo the curve order
scalarMul :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Scalar curve -> Scalar curve
-- | An elliptic curve key pair composed of the private part (a scalar),
-- and the associated point.
data KeyPair curve
KeyPair :: !Point curve -> !Scalar curve -> KeyPair curve
[keypairGetPublic] :: KeyPair curve -> !Point curve
[keypairGetPrivate] :: KeyPair curve -> !Scalar curve
newtype SharedSecret
SharedSecret :: ScrubbedBytes -> SharedSecret
instance Data.Data.Data Crypto.ECC.Curve_Edwards25519
instance GHC.Show.Show Crypto.ECC.Curve_Edwards25519
instance Data.Data.Data Crypto.ECC.Curve_X448
instance GHC.Show.Show Crypto.ECC.Curve_X448
instance Data.Data.Data Crypto.ECC.Curve_X25519
instance GHC.Show.Show Crypto.ECC.Curve_X25519
instance Data.Data.Data Crypto.ECC.Curve_P521R1
instance GHC.Show.Show Crypto.ECC.Curve_P521R1
instance Data.Data.Data Crypto.ECC.Curve_P384R1
instance GHC.Show.Show Crypto.ECC.Curve_P384R1
instance Data.Data.Data Crypto.ECC.Curve_P256R1
instance GHC.Show.Show Crypto.ECC.Curve_P256R1
instance Control.DeepSeq.NFData Crypto.ECC.SharedSecret
instance Data.ByteArray.Types.ByteArrayAccess Crypto.ECC.SharedSecret
instance GHC.Classes.Eq Crypto.ECC.SharedSecret
instance Crypto.ECC.EllipticCurve Crypto.ECC.Curve_Edwards25519
instance Crypto.ECC.EllipticCurveArith Crypto.ECC.Curve_Edwards25519
instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_Edwards25519
instance Crypto.ECC.EllipticCurve Crypto.ECC.Curve_X448
instance Crypto.ECC.EllipticCurveDH Crypto.ECC.Curve_X448
instance Crypto.ECC.EllipticCurve Crypto.ECC.Curve_X25519
instance Crypto.ECC.EllipticCurveDH Crypto.ECC.Curve_X25519
instance Crypto.ECC.EllipticCurve Crypto.ECC.Curve_P521R1
instance Crypto.ECC.EllipticCurveArith Crypto.ECC.Curve_P521R1
instance Crypto.ECC.EllipticCurveDH Crypto.ECC.Curve_P521R1
instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_P521R1
instance Crypto.ECC.EllipticCurve Crypto.ECC.Curve_P384R1
instance Crypto.ECC.EllipticCurveArith Crypto.ECC.Curve_P384R1
instance Crypto.ECC.EllipticCurveDH Crypto.ECC.Curve_P384R1
instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_P384R1
instance Crypto.ECC.EllipticCurve Crypto.ECC.Curve_P256R1
instance Crypto.ECC.EllipticCurveArith Crypto.ECC.Curve_P256R1
instance Crypto.ECC.EllipticCurveDH Crypto.ECC.Curve_P256R1
instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_P256R1
-- | IES with Elliptic curve
-- https://en.wikipedia.org/wiki/Integrated_Encryption_Scheme
--
-- This is a simple cryptographic system between 2 parties using Elliptic
-- Curve.
--
-- The sending party create a shared secret using the receiver public
-- key, and use the shared secret to generate cryptographic material for
-- an symmetric encryption scheme (preferably authenticated encryption).
--
-- The receiving party receive the temporary ephemeral public key which
-- is combined to its secret key to create the shared secret which just
-- like on the sending is used to generate cryptographic material.
--
-- This module doesn't provide any symmetric data encryption capability
-- or any mean to derive cryptographic key material for a symmetric key
-- from the shared secret. this is left to the user for now.
module Crypto.PubKey.ECIES
-- | Generate random a new Shared secret and the associated point to do a
-- ECIES style encryption
deriveEncrypt :: (MonadRandom randomly, EllipticCurveDH curve) => proxy curve -> Point curve -> randomly (CryptoFailable (Point curve, SharedSecret))
-- | Derive the shared secret with the receiver key and the R point of the
-- scheme.
deriveDecrypt :: EllipticCurveDH curve => proxy curve -> Point curve -> Scalar curve -> CryptoFailable SharedSecret
-- | Elliptic Curve Digital Signature Algorithm, with the parameterized
-- curve implementations provided by module Crypto.ECC.
--
-- Public/private key pairs can be generated using
-- curveGenerateKeyPair or decoded from binary.
--
-- WARNING: Only curve P-256 has constant-time implementation.
-- Signature operations with P-384 and P-521 may leak the private key.
--
-- Signature verification should be safe for all curves.
module Crypto.PubKey.ECDSA
-- | Elliptic curves with ECDSA capabilities.
class EllipticCurveBasepointArith curve => EllipticCurveECDSA curve
-- | Is a scalar in the accepted range for ECDSA
scalarIsValid :: EllipticCurveECDSA curve => proxy curve -> Scalar curve -> Bool
-- | Test whether the scalar is zero
scalarIsZero :: EllipticCurveECDSA curve => proxy curve -> Scalar curve -> Bool
-- | Scalar inversion modulo the curve order
scalarInv :: EllipticCurveECDSA curve => proxy curve -> Scalar curve -> Maybe (Scalar curve)
-- | Return the point X coordinate as a scalar
pointX :: EllipticCurveECDSA curve => proxy curve -> Point curve -> Maybe (Scalar curve)
-- | ECDSA Public Key.
type PublicKey curve = Point curve
-- | Encode a public key into binary form, i.e. the uncompressed encoding
-- referenced from RFC 5480 section 2.2.
encodePublic :: (EllipticCurve curve, ByteArray bs) => proxy curve -> PublicKey curve -> bs
-- | Try to decode the binary form of a public key.
decodePublic :: (EllipticCurve curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (PublicKey curve)
-- | Create a public key from a private key.
toPublic :: EllipticCurveECDSA curve => proxy curve -> PrivateKey curve -> PublicKey curve
-- | ECDSA Private Key.
type PrivateKey curve = Scalar curve
-- | Encode a private key into binary form, i.e. the privateKey
-- field described in RFC 5915.
encodePrivate :: (EllipticCurveECDSA curve, ByteArray bs) => proxy curve -> PrivateKey curve -> bs
-- | Try to decode the binary form of a private key.
decodePrivate :: (EllipticCurveECDSA curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (PrivateKey curve)
-- | Represent a ECDSA signature namely R and S.
data Signature curve
Signature :: Scalar curve -> Scalar curve -> Signature curve
-- | ECDSA r
[sign_r] :: Signature curve -> Scalar curve
-- | ECDSA s
[sign_s] :: Signature curve -> Scalar curve
-- | Create a signature from integers (R, S).
signatureFromIntegers :: EllipticCurveECDSA curve => proxy curve -> (Integer, Integer) -> CryptoFailable (Signature curve)
-- | Get integers (R, S) from a signature.
--
-- The values can then be used to encode the signature to binary with
-- ASN.1.
signatureToIntegers :: EllipticCurveECDSA curve => proxy curve -> Signature curve -> (Integer, Integer)
-- | Sign message using the private key and an explicit k scalar.
signWith :: (EllipticCurveECDSA curve, ByteArrayAccess msg, HashAlgorithm hash) => proxy curve -> Scalar curve -> PrivateKey curve -> hash -> msg -> Maybe (Signature curve)
-- | Sign digest using the private key and an explicit k scalar.
signDigestWith :: (EllipticCurveECDSA curve, HashAlgorithm hash) => proxy curve -> Scalar curve -> PrivateKey curve -> Digest hash -> Maybe (Signature curve)
-- | Sign a message using hash and private key.
sign :: (EllipticCurveECDSA curve, MonadRandom m, ByteArrayAccess msg, HashAlgorithm hash) => proxy curve -> PrivateKey curve -> hash -> msg -> m (Signature curve)
-- | Sign a digest using hash and private key.
signDigest :: (EllipticCurveECDSA curve, MonadRandom m, HashAlgorithm hash) => proxy curve -> PrivateKey curve -> Digest hash -> m (Signature curve)
-- | Verify a signature using hash and public key.
verify :: (EllipticCurveECDSA curve, ByteArrayAccess msg, HashAlgorithm hash) => proxy curve -> hash -> PublicKey curve -> Signature curve -> msg -> Bool
-- | Verify a digest using hash and public key.
verifyDigest :: (EllipticCurveECDSA curve, HashAlgorithm hash) => proxy curve -> PublicKey curve -> Signature curve -> Digest hash -> Bool
instance GHC.Classes.Eq (Crypto.ECC.Scalar curve) => GHC.Classes.Eq (Crypto.PubKey.ECDSA.Signature curve)
instance GHC.Show.Show (Crypto.ECC.Scalar curve) => GHC.Show.Show (Crypto.PubKey.ECDSA.Signature curve)
instance Crypto.PubKey.ECDSA.EllipticCurveECDSA Crypto.ECC.Curve_P256R1
instance Crypto.PubKey.ECDSA.EllipticCurveECDSA Crypto.ECC.Curve_P384R1
instance Crypto.PubKey.ECDSA.EllipticCurveECDSA Crypto.ECC.Curve_P521R1
instance Control.DeepSeq.NFData (Crypto.ECC.Scalar curve) => Control.DeepSeq.NFData (Crypto.PubKey.ECDSA.Signature curve)
-- | Haskell implementation of the Anti-forensic information splitter
-- available in LUKS. http://clemens.endorphin.org/AFsplitter
--
-- The algorithm bloats an arbitrary secret with many bits that are
-- necessary for the recovery of the key (merge), and allow greater way
-- to permanently destroy a key stored on disk.
module Crypto.Data.AFIS
-- | Split data to diffused data, using a random generator and an hash
-- algorithm.
--
-- the diffused data will consist of random data for (expandTimes-1) then
-- the last block will be xor of the accumulated random data diffused by
-- the hash algorithm.
--
--
-- - ---------
-- - orig -
-- - ---------
-- - --------- ---------- --------------
-- - rand1 - - rand2 - - orig ^ acc -
-- - --------- ---------- --------------
--
--
-- where acc is : acc(n+1) = hash (n ++ rand(n)) ^ acc(n)
split :: (ByteArray ba, HashAlgorithm hash, DRG rng) => hash -> rng -> Int -> ba -> (ba, rng)
-- | Merge previously diffused data back to the original data.
merge :: (ByteArray ba, HashAlgorithm hash) => hash -> Int -> ba -> ba
-- | Gives information about cryptonite runtime environment.
module Crypto.System.CPU
-- | CPU options impacting cryptography implementation and library
-- performance.
data ProcessorOption
-- | Support for AES instructions, with flag support_aesni
AESNI :: ProcessorOption
-- | Support for CLMUL instructions, with flag support_pclmuldq
PCLMUL :: ProcessorOption
-- | Support for RDRAND instruction, with flag support_rdrand
RDRAND :: ProcessorOption
-- | Options which have been enabled at compile time and are supported by
-- the current CPU.
processorOptions :: [ProcessorOption]
instance Data.Data.Data Crypto.System.CPU.ProcessorOption
instance GHC.Enum.Enum Crypto.System.CPU.ProcessorOption
instance GHC.Classes.Eq Crypto.System.CPU.ProcessorOption
instance GHC.Show.Show Crypto.System.CPU.ProcessorOption
-- | Examples of how to use cryptonite.
module Crypto.Tutorial