8n      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmportable experimental!dominic.steinitz@blueyonder.co.ukn op    portablebetaThomas.DuBuisson@gmail.com%Handle for manual resource mangement qOpen a   Close the  Read random data from a  BInefficiently get a specific number of bytes of cryptographically : secure random data using the system-specific facilities. Use '/dev/urandom'' on *nix and CryptAPI when on Windows. r portable betaThomas.DuBuisson@gmail.com5Not that it is technically correct as an instance of , but simply because  it'is a reasonable engineering choice here is a CryptoRandomGen which streams the system randoms. Take note: # It uses the default definition of genByteWithEntropy   will always fail!   will always fail! 1 the handle to the system random is never closed sMA class of random bit generators that allows for the possibility of failure, C reseeding, providing entropy at the same time as requesting bytes Minimum complete definition: , , , . HInstantiate a new random bit generator. The provided bytestring should > be of length >= genSeedLength. If the bytestring is shorter * then the call may fail (suggested error: ! ). If the C bytestring is of sufficent length the call should always succeed. GLength of input entropy necessary to instantiate or reseed a generator genBytes len g) generates a random ByteString of length len and new generator.  The MonadCryptoRandom; package has routines useful for converting the ByteString  to commonly needed values (but cereal6 or other deserialization libraries would also work). XThis routine can fail if the generator has gone too long without a reseed (usually this J is in the ball-park of 2^48 requests). Suggested error in this cases is " genBytesWithEntropy g i entropy generates i random bytes and use the  additional input entropy, in the generation of the requested data to G increase the confidence our generated data is a secure random stream. Some generators use entropy1 to perturb the state of the generator, meaning:    (_,g2') <!- genBytesWithEntropy len g1 ent  (_,g2 ) <- genBytes len g1  g2 /= g2' But this is not required.  Default:  J genBytesWithEntropy g bytes entropy = xor entropy (genBytes g bytes) IIf the generator has produced too many random bytes on its existing seed  it will throw ">. In that case, reseed the generator using this function and & a new high-entropy seed of length >= (. Using bytestrings that are too short  can result in an error (!). By default this uses System.Crypto.Random to obtain entropy for . 6many generators have these error conditions in common KThis generator can not be instantiated or reseeded with a finite seed (ex: ) !0For instantiating new generators (or reseeding) "]Some generators cease operation after too high a count without a reseed (ex: NIST SP 800-90) # When using genInteger g (l,h) and %logBase 2 (h - l) > (maxBound :: Int). $bRequested more bytes than a single pass can generate (The maximum request is generator dependent) %Misc tJget a random number generator based on the standard system entropy source &u:Obtain a tagged value for a particular instantiated type. v !"#$%&%$#"! &%$#"! !"#$%& portable betaThomas.DuBuisson@gmail.com%'FA class for signing operations which inherently can not be as generic ! as asymetric ciphers (ex: DSA). ()*+,-WA stream cipher class. Instance are expected to work on messages as small as one byte 9 The length of the resulting cipher text should be equal % to the length of the input message. ./0126Asymetric ciphers (common ones being RSA or EC based) 3build a public/.private key pair using the provided generator 4Asymetric encryption 5Asymetric decryption 678;The BlockCipher class is intended as the generic interface < targeted by maintainers of Haskell cipher implementations. 5 Using this generic interface higher level functions  such as cbcC, and other functions from Data.Crypto.Modes, provide a useful API * for comsumers of cipher implementations. %Instances must handle unaligned data 9LThe size of a single block; the smallest unit on which the cipher operates. :encrypt data of size  n*blockSize where n w [0..] (ecb encryption) ;decrypt data of size  n*blockSize where n w [0..] (ecb decryption) <.smart constructor for keys from a bytestring. =8keyLength may inspect its argument to return the length >4The Hash class is intended as the generic interface < targeted by maintainers of Haskell digest implementations. 6 Using this generic interface, higher level functions  such as D and E provide a useful API ( for comsumers of hash implementations. ;Any instantiated implementation must handle unaligned data ?$The size of the digest when encoded @GThe amount of data operated on in each round of the digest computation A4An initial context, provided with the first call to B BHUsed to update a context, repeatedly called until all data is exhausted ( must operate correctly for imputs of  n*blockLength bytes for n w [0..] CUFinializing a context, plus any message data less than the block size, into a digest D*Hash a lazy ByteString, creating a digest E,Hash a strict ByteString, creating a digest F*Obtain a lazy hash function from a digest G,Obtain a strict hash function from a digest xH'Obtain a tagged value for a given type IInfix H operator J$'()*+,-./0123456789:;<=>?@ABCDEFGHIJ$>?@ABC89:;<=J-./01234567'()*+,HIDEFG$'()*+,()*+,-./01./012345673456789:;<=9:;<=>?@ABC?@ABCDEFGHIJ portable betaThomas.DuBuisson@gmail.comKLM>Message authentication code calculation for lazy bytestrings.   hmac k msg) will compute an authentication code for msg using key k N hmac k msg) will compute an authentication code for msg using key k KLMNMNKLKLLMN portable betaThomas.DuBuisson@gmail.comOFInitilization Vectors for BlockCipher implementations (IV k) are used J for various modes and guarrenteed to be blockSize bits long. The common + ways to obtain an IV are to generate one (b or c) or to 1 use one provided with the ciphertext (using the y instance of IV). z{|}~PzipWith xor + Pack C This is written intentionally to take advantage of the bytestring  libraries zipWith'+ rewrite rule but at the extra cost of the D resulting lazy bytestring being more fragmented than either of the  two inputs. zipWith xor + Pack Y As a result of rewrite rules, this should automatically be optimized (at compile time) ! to use the bytestring libraries zipWith' function. <Cipher block chaining encryption mode on strict bytestrings QRS8Cipher block chaining decryption for strict bytestrings T6Cipher block chaining encryption for lazy bytestrings U6Cipher block chaining decryption for lazy bytestrings VWXYZPCiphertext feed-back encryption mode for lazy bytestrings (with s == blockSize) [PCiphertext feed-back decryption mode for lazy bytestrings (with s == blockSize) \RCiphertext feed-back encryption mode for strict bytestrings (with s == blockSize) ]RCiphertext feed-back decryption mode for strict bytestrings (with s == blockSize) ^*Output feedback mode for lazy bytestrings _*Output feedback mode for lazy bytestrings `,Output feedback mode for strict bytestrings a,Output feedback mode for strict bytestrings b Obtain an O+ using the provided CryptoRandomGenerator. c Obtain an O using the system entropy (see System.Crypto.Random) OPQRSTUVWXYZ[\]^_`abcObcVWTUZ[^_XYPS\]`aQROPQRSTUVWXYZ[\]^_`abc d$PKCS5 (aka RFC1423) padding method. : This method will not work properly for pad modulos > 256 e   putPaddedPKCS5 m bs  Will pad out bs to a byte multiple  of m# and put both the bytestring and it's padding via  : (this saves on copying if you are already using Cereal). fBPKCS5 (aka RFC1423) padding method using the BlockCipher instance  to determine the pad size.  Leverages e# to put the bytestring and padding = of sufficient length for use by the specified block cipher. g>unpad a strict bytestring padded in the typical PKCS5 manner. E This routine verifies all pad bytes and pad length match correctly. h]unpad a strict bytestring without checking the pad bytes and length any more than necessary. i0Pad a bytestring to the IPSEC esp specification   padESP m payload is equivilent to:   : (msg) (padding) (length field) ) B.concat [payload, B.pack [1,2,3,4..], B.pack [padLen]] Where: ( the msg is any payload, including TFC.  the padding is <= 255  the length field is one byte. -Notice the result bytesting length remainder r equals zero. The lack  of a " next header"7 field means this function is not directly useable for  an IPSec implementation (copy/'paste the 4 line function and add in a  " next header"% field if you are making IPSec ESP). jGLike padESP but use the BlockCipher instance to determine padding size kLLike putPadESP but using the BlockCipher instance to determine padding size l6Pad a bytestring to the IPSEC ESP specification using . 2 This can reduce copying if you are already using . m/A static espPad allows reuse of a single B.pack'ed pad for all calls to padESP Tunpad and return the padded message (Nothing is returned if the padding is invalid) defghijklm dfeghimjkl defghijklm      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{Q|}~Wcrypto-api-0.4.1Data.LargeWord Crypto.TypesSystem.Crypto.Random Crypto.RandomCrypto.Classes Crypto.HMAC Crypto.ModesCrypto.PaddingWord256Word224Word192Word160Word128Word96LargeKey LargeWordlargeWordToIntegerintegerToLargeWord largeWordPlus largeWordAnd largeWordOrlargeWordShift largeWordXor largeBitSize ByteLength BitLength CryptHandle openHandle closeHandle hGetEntropy getEntropy SystemRandomCryptoRandomGennewGen genSeedLengthgenBytesgenBytesWithEntropyreseednewGenIOGenErrorNeedsInfiniteSeedNotEnoughEntropy NeedReseed RangeInvalidRequestedTooManyBytes GenErrorOthersplitGenSigningsignverifybuildSigningPairsigningKeyLengthverifyingKeyLength StreamCipherbuildStreamKey encryptStream decryptStreamstreamKeyLength AsymCipher buildKeyPair encryptAsym decryptAsympublicKeyLengthprivateKeyLength BlockCipher blockSize encryptBlock decryptBlockbuildKey keyLengthHash outputLength blockLength initialCtx updateCtxfinalizehashhash'hashFunc hashFunc'for.::.blockSizeBytesMacKeyhmachmac'IVcbc'cbcMac'cbcMacunCbc'cbcunCbcecbunEcbecb'unEcb'cfbunCfbcfb'unCfb'ofbunOfbofb'unOfb'getIVgetIVIOpadPKCS5putPaddedPKCS5 padBlockSizeunpadPKCS5safe unpadPKCS5padESPpadESPBlockSizeputPadESPBlockSize putPadESPunpadESPaoflkboflkCHgetEnt SysRandom getSystemGenbs2ibaseGHC.Listelem makeBlockscereal-0.3.0.0Data.Serialize SerializeinitializationVectorcollectchunkFor chunkFor'unfoldKivProxy deIVProxyproxyOfivBlockSizeBytesData.Serialize.PutPutputPaddedBlockSize