packages feed

cryptonite 0.26 → 0.27

raw patch · 71 files changed

+4300/−1194 lines, 71 filesPVP ok

version bump matches the API change (PVP)

API changes (from Hackage documentation)

+ Crypto.Cipher.AESGCMSIV: data Nonce
+ Crypto.Cipher.AESGCMSIV: decrypt :: (BlockCipher128 aes, ByteArrayAccess aad, ByteArray ba) => aes -> Nonce -> aad -> ba -> AuthTag -> Maybe ba
+ Crypto.Cipher.AESGCMSIV: encrypt :: (BlockCipher128 aes, ByteArrayAccess aad, ByteArray ba) => aes -> Nonce -> aad -> ba -> (AuthTag, ba)
+ Crypto.Cipher.AESGCMSIV: generateNonce :: MonadRandom m => m Nonce
+ Crypto.Cipher.AESGCMSIV: instance Data.ByteArray.Types.ByteArrayAccess Crypto.Cipher.AESGCMSIV.Nonce
+ Crypto.Cipher.AESGCMSIV: instance GHC.Classes.Eq Crypto.Cipher.AESGCMSIV.Nonce
+ Crypto.Cipher.AESGCMSIV: instance GHC.Show.Show Crypto.Cipher.AESGCMSIV.Nonce
+ Crypto.Cipher.AESGCMSIV: nonce :: ByteArrayAccess iv => iv -> CryptoFailable Nonce
+ Crypto.Cipher.XSalsa: derive :: ByteArrayAccess nonce => State -> nonce -> State
+ Crypto.ECC: class (EllipticCurveArith curve, Eq (Scalar curve)) => EllipticCurveBasepointArith curve
+ Crypto.ECC: curveOrderBits :: EllipticCurveBasepointArith curve => proxy curve -> Int
+ Crypto.ECC: decodeScalar :: (EllipticCurveBasepointArith curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (Scalar curve)
+ Crypto.ECC: encodeScalar :: (EllipticCurveBasepointArith curve, ByteArray bs) => proxy curve -> Scalar curve -> bs
+ Crypto.ECC: instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_Edwards25519
+ Crypto.ECC: instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_P256R1
+ Crypto.ECC: instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_P384R1
+ Crypto.ECC: instance Crypto.ECC.EllipticCurveBasepointArith Crypto.ECC.Curve_P521R1
+ Crypto.ECC: pointBaseSmul :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Point curve
+ Crypto.ECC: pointsSmulVarTime :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Scalar curve -> Point curve -> Point curve
+ Crypto.ECC: scalarAdd :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Scalar curve -> Scalar curve
+ Crypto.ECC: scalarFromInteger :: EllipticCurveBasepointArith curve => proxy curve -> Integer -> CryptoFailable (Scalar curve)
+ Crypto.ECC: scalarMul :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Scalar curve -> Scalar curve
+ Crypto.ECC: scalarToInteger :: EllipticCurveBasepointArith curve => proxy curve -> Scalar curve -> Integer
+ Crypto.Number.F2m: powF2m :: BinaryPolynomial -> Integer -> Integer -> Integer
+ Crypto.Number.F2m: sqrtF2m :: BinaryPolynomial -> Integer -> Integer
+ Crypto.Number.ModArithmetic: instance GHC.Exception.Type.Exception Crypto.Number.ModArithmetic.ModulusAssertionError
+ Crypto.Number.ModArithmetic: instance GHC.Show.Show Crypto.Number.ModArithmetic.ModulusAssertionError
+ Crypto.Number.ModArithmetic: inverseFermat :: Integer -> Integer -> Integer
+ Crypto.Number.ModArithmetic: squareRoot :: Integer -> Integer -> Maybe Integer
+ Crypto.PubKey.ECC.P256: pointIsAtInfinity :: Point -> Bool
+ Crypto.PubKey.ECC.P256: pointX :: Point -> Maybe Scalar
+ Crypto.PubKey.ECC.P256: scalarInvSafe :: Scalar -> Scalar
+ Crypto.PubKey.ECC.P256: scalarMul :: Scalar -> Scalar -> Scalar
+ Crypto.PubKey.ECC.P256: scalarN :: Scalar
+ Crypto.PubKey.ECDSA: Signature :: Scalar curve -> Scalar curve -> Signature curve
+ Crypto.PubKey.ECDSA: [sign_r] :: Signature curve -> Scalar curve
+ Crypto.PubKey.ECDSA: [sign_s] :: Signature curve -> Scalar curve
+ Crypto.PubKey.ECDSA: class EllipticCurveBasepointArith curve => EllipticCurveECDSA curve
+ Crypto.PubKey.ECDSA: data Signature curve
+ Crypto.PubKey.ECDSA: decodePrivate :: (EllipticCurveECDSA curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (PrivateKey curve)
+ Crypto.PubKey.ECDSA: decodePublic :: (EllipticCurve curve, ByteArray bs) => proxy curve -> bs -> CryptoFailable (PublicKey curve)
+ Crypto.PubKey.ECDSA: encodePrivate :: (EllipticCurveECDSA curve, ByteArray bs) => proxy curve -> PrivateKey curve -> bs
+ Crypto.PubKey.ECDSA: encodePublic :: (EllipticCurve curve, ByteArray bs) => proxy curve -> PublicKey curve -> bs
+ Crypto.PubKey.ECDSA: instance Control.DeepSeq.NFData (Crypto.ECC.Scalar curve) => Control.DeepSeq.NFData (Crypto.PubKey.ECDSA.Signature curve)
+ Crypto.PubKey.ECDSA: instance Crypto.PubKey.ECDSA.EllipticCurveECDSA Crypto.ECC.Curve_P256R1
+ Crypto.PubKey.ECDSA: instance Crypto.PubKey.ECDSA.EllipticCurveECDSA Crypto.ECC.Curve_P384R1
+ Crypto.PubKey.ECDSA: instance Crypto.PubKey.ECDSA.EllipticCurveECDSA Crypto.ECC.Curve_P521R1
+ Crypto.PubKey.ECDSA: instance GHC.Classes.Eq (Crypto.ECC.Scalar curve) => GHC.Classes.Eq (Crypto.PubKey.ECDSA.Signature curve)
+ Crypto.PubKey.ECDSA: instance GHC.Show.Show (Crypto.ECC.Scalar curve) => GHC.Show.Show (Crypto.PubKey.ECDSA.Signature curve)
+ Crypto.PubKey.ECDSA: pointX :: EllipticCurveECDSA curve => proxy curve -> Point curve -> Maybe (Scalar curve)
+ Crypto.PubKey.ECDSA: scalarInv :: EllipticCurveECDSA curve => proxy curve -> Scalar curve -> Maybe (Scalar curve)
+ Crypto.PubKey.ECDSA: scalarIsValid :: EllipticCurveECDSA curve => proxy curve -> Scalar curve -> Bool
+ Crypto.PubKey.ECDSA: scalarIsZero :: EllipticCurveECDSA curve => proxy curve -> Scalar curve -> Bool
+ Crypto.PubKey.ECDSA: sign :: (EllipticCurveECDSA curve, MonadRandom m, ByteArrayAccess msg, HashAlgorithm hash) => proxy curve -> PrivateKey curve -> hash -> msg -> m (Signature curve)
+ Crypto.PubKey.ECDSA: signDigest :: (EllipticCurveECDSA curve, MonadRandom m, HashAlgorithm hash) => proxy curve -> PrivateKey curve -> Digest hash -> m (Signature curve)
+ Crypto.PubKey.ECDSA: signDigestWith :: (EllipticCurveECDSA curve, HashAlgorithm hash) => proxy curve -> Scalar curve -> PrivateKey curve -> Digest hash -> Maybe (Signature curve)
+ Crypto.PubKey.ECDSA: signWith :: (EllipticCurveECDSA curve, ByteArrayAccess msg, HashAlgorithm hash) => proxy curve -> Scalar curve -> PrivateKey curve -> hash -> msg -> Maybe (Signature curve)
+ Crypto.PubKey.ECDSA: signatureFromIntegers :: EllipticCurveECDSA curve => proxy curve -> (Integer, Integer) -> CryptoFailable (Signature curve)
+ Crypto.PubKey.ECDSA: signatureToIntegers :: EllipticCurveECDSA curve => proxy curve -> Signature curve -> (Integer, Integer)
+ Crypto.PubKey.ECDSA: toPublic :: EllipticCurveECDSA curve => proxy curve -> PrivateKey curve -> PublicKey curve
+ Crypto.PubKey.ECDSA: type PrivateKey curve = Scalar curve
+ Crypto.PubKey.ECDSA: type PublicKey curve = Point curve
+ Crypto.PubKey.ECDSA: verify :: (EllipticCurveECDSA curve, ByteArrayAccess msg, HashAlgorithm hash) => proxy curve -> hash -> PublicKey curve -> Signature curve -> msg -> Bool
+ Crypto.PubKey.ECDSA: verifyDigest :: (EllipticCurveECDSA curve, HashAlgorithm hash) => proxy curve -> PublicKey curve -> Signature curve -> Digest hash -> Bool
+ Crypto.System.CPU: AESNI :: ProcessorOption
+ Crypto.System.CPU: PCLMUL :: ProcessorOption
+ Crypto.System.CPU: RDRAND :: ProcessorOption
+ Crypto.System.CPU: data ProcessorOption
+ Crypto.System.CPU: instance Data.Data.Data Crypto.System.CPU.ProcessorOption
+ Crypto.System.CPU: instance GHC.Classes.Eq Crypto.System.CPU.ProcessorOption
+ Crypto.System.CPU: instance GHC.Enum.Enum Crypto.System.CPU.ProcessorOption
+ Crypto.System.CPU: instance GHC.Show.Show Crypto.System.CPU.ProcessorOption
+ Crypto.System.CPU: processorOptions :: [ProcessorOption]
- Crypto.ECC: class EllipticCurve curve => EllipticCurveArith curve
+ Crypto.ECC: class (EllipticCurve curve, Eq (Point curve)) => EllipticCurveArith curve
- Crypto.Random: class (Functor m, Monad m) => MonadRandom m
+ Crypto.Random: class Monad m => MonadRandom m
- Crypto.Random.Types: class (Functor m, Monad m) => MonadRandom m
+ Crypto.Random.Types: class Monad m => MonadRandom m

Files

CHANGELOG.md view
@@ -1,3 +1,13 @@+## 0.27++* Optimise AES GCM and CCM+* Optimise P256R1 implementation+* Various AES-NI building improvements+* Add better ECDSA support+* Add XSalsa derive+* Implement square roots for ECC binary curve+* Various tests and benchmarks+ ## 0.26  * Add Rabin cryptosystem (and variants)
Crypto/Cipher/AES/Primitive.hs view
@@ -37,6 +37,9 @@     , decryptCTR     , decryptXTS +    -- * CTR with 32-bit wrapping+    , combineC32+     -- * Incremental GCM     , gcmMode     , gcmInit@@ -128,7 +131,7 @@     deriving (NFData)  sizeGCM :: Int-sizeGCM = 80+sizeGCM = 320  sizeOCB :: Int sizeOCB = 160@@ -317,6 +320,21 @@            -> ba         -- ^ output decrypted decryptXTS = doXTS c_aes_decrypt_xts +-- | encrypt/decrypt using Counter mode (32-bit wrapping used in AES-GCM-SIV)+{-# NOINLINE combineC32 #-}+combineC32 :: ByteArray ba+           => AES        -- ^ AES Context+           -> IV AES     -- ^ initial vector of AES block size (usually representing a 128 bit integer)+           -> ba         -- ^ plaintext input+           -> ba         -- ^ ciphertext output+combineC32 ctx iv input+    | len <= 0          = B.empty+    | B.length iv /= 16 = error $ "AES error: IV length must be block size (16). Its length is: " ++ show (B.length iv)+    | otherwise = B.allocAndFreeze len doEncrypt+  where doEncrypt o = withKeyAndIV ctx iv $ \k v -> withByteArray input $ \i ->+                      c_aes_encrypt_c32 (castPtr o) k v i (fromIntegral len)+        len = B.length input+ {-# INLINE doECB #-} doECB :: ByteArray ba       => (Ptr b -> Ptr AES -> CString -> CUInt -> IO ())@@ -577,6 +595,9 @@  foreign import ccall "cryptonite_aes.h cryptonite_aes_encrypt_ctr"     c_aes_encrypt_ctr :: CString -> Ptr AES -> Ptr Word8 -> CString -> CUInt -> IO ()++foreign import ccall "cryptonite_aes.h cryptonite_aes_encrypt_c32"+    c_aes_encrypt_c32 :: CString -> Ptr AES -> Ptr Word8 -> CString -> CUInt -> IO ()  foreign import ccall "cryptonite_aes.h cryptonite_aes_gcm_init"     c_aes_gcm_init :: Ptr AESGCM -> Ptr AES -> Ptr Word8 -> CUInt -> IO ()
+ Crypto/Cipher/AESGCMSIV.hs view
@@ -0,0 +1,193 @@+-- |+-- Module      : Crypto.Cipher.AESGCMSIV+-- License     : BSD-style+-- Maintainer  : Olivier Chéron <olivier.cheron@gmail.com>+-- Stability   : experimental+-- Portability : unknown+--+-- Implementation of AES-GCM-SIV, an AEAD scheme with nonce misuse resistance+-- defined in <https://tools.ietf.org/html/rfc8452 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.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+module Crypto.Cipher.AESGCMSIV+    ( Nonce+    , nonce+    , generateNonce+    , encrypt+    , decrypt+    ) where++import Data.Bits+import Data.Word++import Foreign.C.Types+import Foreign.C.String+import Foreign.Ptr (Ptr, plusPtr)+import Foreign.Storable (peekElemOff, poke, pokeElemOff)++import           Data.ByteArray+import qualified Data.ByteArray as B+import           Data.Memory.Endian (toLE)+import           Data.Memory.PtrMethods (memXor)++import Crypto.Cipher.AES.Primitive+import Crypto.Cipher.Types+import Crypto.Error+import Crypto.Internal.Compat (unsafeDoIO)+import Crypto.Random+++-- 12-byte nonces++-- | Nonce value for AES-GCM-SIV, always 12 bytes.+newtype Nonce = Nonce Bytes deriving (Show, Eq, ByteArrayAccess)++-- | Nonce smart constructor.  Accepts only 12-byte inputs.+nonce :: ByteArrayAccess iv => iv -> CryptoFailable Nonce+nonce iv+    | B.length iv == 12 = CryptoPassed (Nonce $ B.convert iv)+    | otherwise         = CryptoFailed CryptoError_IvSizeInvalid++-- | Generate a random nonce for use with AES-GCM-SIV.+generateNonce :: MonadRandom m => m Nonce+generateNonce = Nonce <$> getRandomBytes 12+++-- POLYVAL (mutable context)++newtype Polyval = Polyval Bytes++polyvalInit :: ScrubbedBytes -> IO Polyval+polyvalInit h = Polyval <$> doInit+  where doInit = B.alloc 272 $ \pctx -> B.withByteArray h $ \ph ->+            c_aes_polyval_init pctx ph++polyvalUpdate :: ByteArrayAccess ba => Polyval -> ba -> IO ()+polyvalUpdate (Polyval ctx) bs = B.withByteArray ctx $ \pctx ->+    B.withByteArray bs $ \pbs -> c_aes_polyval_update pctx pbs sz+  where sz = fromIntegral (B.length bs)++polyvalFinalize :: Polyval -> IO ScrubbedBytes+polyvalFinalize (Polyval ctx) = B.alloc 16 $ \dst ->+    B.withByteArray ctx $ \pctx -> c_aes_polyval_finalize pctx dst++foreign import ccall unsafe "cryptonite_aes.h cryptonite_aes_polyval_init"+    c_aes_polyval_init :: Ptr Polyval -> CString -> IO ()++foreign import ccall "cryptonite_aes.h cryptonite_aes_polyval_update"+    c_aes_polyval_update :: Ptr Polyval -> CString -> CUInt -> IO ()++foreign import ccall unsafe "cryptonite_aes.h cryptonite_aes_polyval_finalize"+    c_aes_polyval_finalize :: Ptr Polyval -> CString -> IO ()+++-- Key Generation++le32iv :: Word32 -> Nonce -> Bytes+le32iv n (Nonce iv) = B.allocAndFreeze 16 $ \ptr -> do+    poke ptr (toLE n)+    copyByteArrayToPtr iv (ptr `plusPtr` 4)++deriveKeys :: BlockCipher128 aes => aes -> Nonce -> (ScrubbedBytes, AES)+deriveKeys aes iv =+    case cipherKeySize aes of+        KeySizeFixed sz | sz `mod` 8 == 0 ->+            let mak = buildKey [0 .. 1]+                key = buildKey [2 .. fromIntegral (sz `div` 8) + 1]+                mek = throwCryptoError (cipherInit key)+             in (mak, mek)+        _ -> error "AESGCMSIV: invalid cipher"+  where+    idx n = ecbEncrypt aes (le32iv n iv) `takeView` 8+    buildKey = B.concat . map idx+++-- Encryption and decryption++lengthInvalid :: ByteArrayAccess ba => ba -> Bool+lengthInvalid bs+    | finiteBitSize len > 32 = len >= 1 `unsafeShiftL` 32+    | otherwise              = False+  where len = B.length bs++-- | AEAD encryption with the specified key and nonce.  The key must be given+-- as an initialized 'Crypto.Cipher.AES.AES128' or 'Crypto.Cipher.AES.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)+encrypt aes iv aad plaintext+    | lengthInvalid aad = error "AESGCMSIV: aad is too large"+    | lengthInvalid plaintext = error "AESGCMSIV: plaintext is too large"+    | otherwise = (AuthTag tag, ciphertext)+  where+    (mak, mek) = deriveKeys aes iv+    ss = getSs mak aad plaintext+    tag = buildTag mek ss iv+    ciphertext = combineC32 mek (transformTag tag) plaintext++-- | AEAD decryption with the specified key and nonce.  The key must be given+-- as an initialized 'Crypto.Cipher.AES.AES128' or 'Crypto.Cipher.AES.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+decrypt aes iv aad ciphertext (AuthTag tag)+    | lengthInvalid aad = error "AESGCMSIV: aad is too large"+    | lengthInvalid ciphertext = error "AESGCMSIV: ciphertext is too large"+    | tag `constEq` buildTag mek ss iv = Just plaintext+    | otherwise = Nothing+  where+    (mak, mek) = deriveKeys aes iv+    ss = getSs mak aad plaintext+    plaintext = combineC32 mek (transformTag tag) ciphertext++-- Calculate S_s = POLYVAL(mak, X_1, X_2, ...).+getSs :: (ByteArrayAccess aad, ByteArrayAccess ba)+      => ScrubbedBytes -> aad -> ba -> ScrubbedBytes+getSs mak aad plaintext = unsafeDoIO $ do+    ctx <- polyvalInit mak+    polyvalUpdate ctx aad+    polyvalUpdate ctx plaintext+    polyvalUpdate ctx (lb :: Bytes)  -- the "length block"+    polyvalFinalize ctx+  where+    lb = B.allocAndFreeze 16 $ \ptr -> do+            pokeElemOff ptr 0 (toLE64 $ B.length aad)+            pokeElemOff ptr 1 (toLE64 $ B.length plaintext)+    toLE64 x = toLE (fromIntegral x * 8 :: Word64)++-- XOR the first 12 bytes of S_s with the nonce and clear the most significant+-- bit of the last byte.+tagInput :: ScrubbedBytes -> Nonce -> Bytes+tagInput ss (Nonce iv) =+    B.copyAndFreeze ss $ \ptr ->+    B.withByteArray iv $ \ivPtr -> do+        memXor ptr ptr ivPtr 12+        b <- peekElemOff ptr 15+        pokeElemOff ptr 15 (b .&. (0x7f :: Word8))++-- Encrypt the result with AES using the message-encryption key to produce the+-- tag.+buildTag :: BlockCipher128 aes => aes -> ScrubbedBytes -> Nonce -> Bytes+buildTag mek ss iv = ecbEncrypt mek (tagInput ss iv)++-- The initial counter block is the tag with the most significant bit of the+-- last byte set to one.+transformTag :: Bytes -> IV AES+transformTag tag = toIV $ B.copyAndFreeze tag $ \ptr ->+    peekElemOff ptr 15 >>= pokeElemOff ptr 15 . (.|. (0x80 :: Word8))+  where toIV bs = let Just iv = makeIV (bs :: Bytes) in iv
Crypto/Cipher/ChaCha.hs view
@@ -41,9 +41,9 @@            -> nonce -- ^ the nonce (64 or 96 bits)            -> State -- ^ the initial ChaCha state initialize nbRounds key nonce-    | not (kLen `elem` [16,32])       = error "ChaCha: key length should be 128 or 256 bits"-    | not (nonceLen `elem` [8,12])    = error "ChaCha: nonce length should be 64 or 96 bits"-    | not (nbRounds `elem` [8,12,20]) = error "ChaCha: rounds should be 8, 12 or 20"+    | kLen `notElem` [16,32]          = error "ChaCha: key length should be 128 or 256 bits"+    | nonceLen `notElem` [8,12]       = error "ChaCha: nonce length should be 64 or 96 bits"+    | nbRounds `notElem` [8,12,20]    = error "ChaCha: rounds should be 8, 12 or 20"     | otherwise                       = unsafeDoIO $ do         stPtr <- B.alloc 132 $ \stPtr ->             B.withByteArray nonce $ \noncePtr  ->
Crypto/Cipher/Salsa.hs view
@@ -33,9 +33,9 @@            -> nonce  -- ^ the nonce (64 or 96 bits)            -> State  -- ^ the initial Salsa state initialize nbRounds key nonce-    | not (kLen `elem` [16,32])       = error "Salsa: key length should be 128 or 256 bits"-    | not (nonceLen `elem` [8,12])    = error "Salsa: nonce length should be 64 or 96 bits"-    | not (nbRounds `elem` [8,12,20]) = error "Salsa: rounds should be 8, 12 or 20"+    | kLen `notElem` [16,32]          = error "Salsa: key length should be 128 or 256 bits"+    | nonceLen `notElem` [8,12]       = error "Salsa: nonce length should be 64 or 96 bits"+    | nbRounds `notElem` [8,12,20]    = error "Salsa: rounds should be 8, 12 or 20"     | otherwise = unsafeDoIO $ do         stPtr <- B.alloc 132 $ \stPtr ->             B.withByteArray nonce $ \noncePtr  ->
Crypto/Cipher/XSalsa.hs view
@@ -12,6 +12,7 @@ {-# LANGUAGE ForeignFunctionInterface #-} module Crypto.Cipher.XSalsa     ( initialize+    , derive     , combine     , generate     , State@@ -34,7 +35,7 @@ initialize nbRounds key nonce     | kLen /= 32                      = error "XSalsa: key length should be 256 bits"     | nonceLen /= 24                  = error "XSalsa: nonce length should be 192 bits"-    | not (nbRounds `elem` [8,12,20]) = error "XSalsa: rounds should be 8, 12 or 20"+    | nbRounds `notElem` [8,12,20]    = error "XSalsa: rounds should be 8, 12 or 20"     | otherwise = unsafeDoIO $ do         stPtr <- B.alloc 132 $ \stPtr ->             B.withByteArray nonce $ \noncePtr  ->@@ -44,5 +45,31 @@   where kLen     = B.length key         nonceLen = B.length nonce +-- | 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  -- ^ base XSalsa state+       -> nonce  -- ^ the remainder nonce (128 bits)+       -> State  -- ^ the new XSalsa state+derive (State stPtr') nonce+    | nonceLen /= 16 = error "XSalsa: nonce length should be 128 bits"+    | otherwise = unsafeDoIO $ do+        stPtr <- B.copy stPtr' $ \stPtr ->+            B.withByteArray nonce $ \noncePtr  ->+                ccryptonite_xsalsa_derive stPtr nonceLen noncePtr+        return $ State stPtr+  where nonceLen = B.length nonce+ foreign import ccall "cryptonite_xsalsa_init"     ccryptonite_xsalsa_init :: Ptr State -> Int -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> IO ()++foreign import ccall "cryptonite_xsalsa_derive"+    ccryptonite_xsalsa_derive :: Ptr State -> Int -> Ptr Word8 -> IO ()
Crypto/ConstructHash/MiyaguchiPreneel.hs view
@@ -44,7 +44,7 @@       where         (hd, tl) = B.splitAt bsz msg --- | Compute Miyaguchi-Preneel one way compress using the infered block cipher.+-- | 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/
Crypto/Data/Padding.hs view
@@ -6,7 +6,7 @@ -- Portability : unknown -- -- Various cryptographic padding commonly used for block ciphers--- or assymetric systems.+-- or asymmetric systems. -- module Crypto.Data.Padding     ( Format(..)
Crypto/ECC.hs view
@@ -8,6 +8,7 @@ -- Elliptic Curve Cryptography -- {-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-}@@ -21,6 +22,7 @@     , EllipticCurve(..)     , EllipticCurveDH(..)     , EllipticCurveArith(..)+    , EllipticCurveBasepointArith(..)     , KeyPair(..)     , SharedSecret(..)     ) where@@ -34,7 +36,9 @@ import           Crypto.Internal.Imports import           Crypto.Internal.ByteArray (ByteArray, ByteArrayAccess, ScrubbedBytes) import qualified Crypto.Internal.ByteArray as B+import           Crypto.Number.Basic (numBits) import           Crypto.Number.Serialize (i2ospOf_, os2ip)+import qualified Crypto.Number.Serialize.LE as LE import qualified Crypto.PubKey.Curve25519 as X25519 import qualified Crypto.PubKey.Curve448 as X448 import           Data.ByteArray (convert)@@ -98,7 +102,7 @@     -- value or an exception.     ecdh :: proxy curve -> Scalar curve -> Point curve -> CryptoFailable SharedSecret -class EllipticCurve curve => EllipticCurveArith curve where+class (EllipticCurve curve, Eq (Point curve)) => EllipticCurveArith curve where     -- | Add points on a curve     pointAdd :: proxy curve -> Point curve -> Point curve -> Point curve @@ -111,6 +115,35 @@ --   -- | Scalar Inverse --   scalarInverse :: Scalar curve -> Scalar curve +class (EllipticCurveArith curve, Eq (Scalar curve)) => EllipticCurveBasepointArith curve where+    -- | Get the curve order size in bits+    curveOrderBits :: proxy curve -> Int++    -- | Multiply a scalar with the curve base point+    pointBaseSmul :: proxy curve -> Scalar curve -> Point curve++    -- | Multiply the point @p@ with @s2@ and add a lifted to curve value @s1@+    pointsSmulVarTime :: proxy curve -> Scalar curve -> Scalar curve -> Point curve -> Point curve+    pointsSmulVarTime prx s1 s2 p = pointAdd prx (pointBaseSmul prx s1) (pointSmul prx s2 p)++    -- | Encode an elliptic curve scalar into big-endian form+    encodeScalar :: ByteArray bs => proxy curve -> Scalar curve -> bs++    -- | Try to decode the big-endian form of an elliptic curve scalar+    decodeScalar :: ByteArray bs => proxy curve -> bs -> CryptoFailable (Scalar curve)++    -- | Convert an elliptic curve scalar to an integer+    scalarToInteger :: proxy curve -> Scalar curve -> Integer++    -- | Try to create an elliptic curve scalar from an integer+    scalarFromInteger :: proxy curve -> Integer -> CryptoFailable (Scalar curve)++    -- | Add two scalars and reduce modulo the curve order+    scalarAdd :: proxy curve -> Scalar curve -> Scalar curve -> Scalar curve++    -- | Multiply two scalars and reduce modulo the curve order+    scalarMul :: proxy curve -> Scalar curve -> Scalar curve -> Scalar curve+ -- | P256 Curve -- -- also known as P256@@ -133,11 +166,11 @@             uncompressed = B.singleton 4             xy = P256.pointToBinary p     decodePoint _ mxy = case B.uncons mxy of-        Nothing -> CryptoFailed $ CryptoError_PointSizeInvalid+        Nothing -> CryptoFailed CryptoError_PointSizeInvalid         Just (m,xy)             -- uncompressed             | m == 4 -> P256.pointFromBinary xy-            | otherwise -> CryptoFailed $ CryptoError_PointFormatInvalid+            | otherwise -> CryptoFailed CryptoError_PointFormatInvalid  instance EllipticCurveArith Curve_P256R1 where     pointAdd  _ a b = P256.pointAdd a b@@ -148,6 +181,17 @@     ecdhRaw _ s p = SharedSecret $ P256.pointDh s p     ecdh  prx s p = checkNonZeroDH (ecdhRaw prx s p) +instance EllipticCurveBasepointArith Curve_P256R1 where+    curveOrderBits _ = 256+    pointBaseSmul _ = P256.toPoint+    pointsSmulVarTime _ = P256.pointsMulVarTime+    encodeScalar _ = P256.scalarToBinary+    decodeScalar _ = P256.scalarFromBinary+    scalarToInteger _ = P256.scalarToInteger+    scalarFromInteger _ = P256.scalarFromInteger+    scalarAdd _ = P256.scalarAdd+    scalarMul _ = P256.scalarMul+ data Curve_P384R1 = Curve_P384R1     deriving (Show,Data) @@ -171,6 +215,17 @@       where         prx = Proxy :: Proxy Simple.SEC_p384r1 +instance EllipticCurveBasepointArith Curve_P384R1 where+    curveOrderBits _ = 384+    pointBaseSmul _ = Simple.pointBaseMul+    pointsSmulVarTime _ = ecPointsMulVarTime+    encodeScalar _ = ecScalarToBinary+    decodeScalar _ = ecScalarFromBinary+    scalarToInteger _ = ecScalarToInteger+    scalarFromInteger _ = ecScalarFromInteger+    scalarAdd _ = ecScalarAdd+    scalarMul _ = ecScalarMul+ data Curve_P521R1 = Curve_P521R1     deriving (Show,Data) @@ -194,6 +249,17 @@       where         prx = Proxy :: Proxy Simple.SEC_p521r1 +instance EllipticCurveBasepointArith Curve_P521R1 where+    curveOrderBits _ = 521+    pointBaseSmul _ = Simple.pointBaseMul+    pointsSmulVarTime _ = ecPointsMulVarTime+    encodeScalar _ = ecScalarToBinary+    decodeScalar _ = ecScalarFromBinary+    scalarToInteger _ = ecScalarToInteger+    scalarFromInteger _ = ecScalarFromInteger+    scalarAdd _ = ecScalarAdd+    scalarMul _ = ecScalarMul+ data Curve_X25519 = Curve_X25519     deriving (Show,Data) @@ -250,6 +316,22 @@     pointNegate _ p = Edwards25519.pointNegate p     pointSmul _ s p = Edwards25519.pointMul s p +instance EllipticCurveBasepointArith Curve_Edwards25519 where+    curveOrderBits _ = 253+    pointBaseSmul _ = Edwards25519.toPoint+    pointsSmulVarTime _ = Edwards25519.pointsMulVarTime+    encodeScalar _ = B.reverse . Edwards25519.scalarEncode+    decodeScalar _ bs+        | B.length bs == 32 = Edwards25519.scalarDecodeLong (B.reverse bs)+        | otherwise         = CryptoFailed CryptoError_SecretKeySizeInvalid+    scalarToInteger _ s = LE.os2ip (Edwards25519.scalarEncode s :: B.Bytes)+    scalarFromInteger _ i =+        case LE.i2ospOf 32 i of+            Nothing -> CryptoFailed CryptoError_SecretKeySizeInvalid+            Just bs -> Edwards25519.scalarDecodeLong (bs :: B.Bytes)+    scalarAdd _ = Edwards25519.scalarAdd+    scalarMul _ = Edwards25519.scalarMul+ checkNonZeroDH :: SharedSecret -> CryptoFailable SharedSecret checkNonZeroDH s@(SharedSecret b)     | B.constAllZero b = CryptoFailed CryptoError_ScalarMultiplicationInvalid@@ -271,7 +353,7 @@  decodeECPoint :: (Simple.Curve curve, ByteArray bs) => bs -> CryptoFailable (Simple.Point curve) decodeECPoint mxy = case B.uncons mxy of-    Nothing     -> CryptoFailed $ CryptoError_PointSizeInvalid+    Nothing     -> CryptoFailed CryptoError_PointSizeInvalid     Just (m,xy)         -- uncompressed         | m == 4 ->@@ -280,4 +362,47 @@                 x = os2ip xb                 y = os2ip yb              in Simple.pointFromIntegers (x,y)-        | otherwise -> CryptoFailed $ CryptoError_PointFormatInvalid+        | otherwise -> CryptoFailed CryptoError_PointFormatInvalid++ecPointsMulVarTime :: forall curve . Simple.Curve curve+                   => Simple.Scalar curve+                   -> Simple.Scalar curve -> Simple.Point curve+                   -> Simple.Point curve+ecPointsMulVarTime n1 = Simple.pointAddTwoMuls n1 g+  where g = Simple.curveEccG $ Simple.curveParameters (Proxy :: Proxy curve)++ecScalarFromBinary :: forall curve bs . (Simple.Curve curve, ByteArrayAccess bs)+                   => bs -> CryptoFailable (Simple.Scalar curve)+ecScalarFromBinary ba+    | B.length ba /= size = CryptoFailed CryptoError_SecretKeySizeInvalid+    | otherwise           = CryptoPassed (Simple.Scalar $ os2ip ba)+  where size = ecCurveOrderBytes (Proxy :: Proxy curve)++ecScalarToBinary :: forall curve bs . (Simple.Curve curve, ByteArray bs)+                 => Simple.Scalar curve -> bs+ecScalarToBinary (Simple.Scalar s) = i2ospOf_ size s+  where size = ecCurveOrderBytes (Proxy :: Proxy curve)++ecScalarFromInteger :: forall curve . Simple.Curve curve+                    => Integer -> CryptoFailable (Simple.Scalar curve)+ecScalarFromInteger s+    | numBits s > nb = CryptoFailed CryptoError_SecretKeySizeInvalid+    | otherwise      = CryptoPassed (Simple.Scalar s)+  where nb = 8 * ecCurveOrderBytes (Proxy :: Proxy curve)++ecScalarToInteger :: Simple.Scalar curve -> Integer+ecScalarToInteger (Simple.Scalar s) = s++ecCurveOrderBytes :: Simple.Curve c => proxy c -> Int+ecCurveOrderBytes prx = (numBits n + 7) `div` 8+  where n = Simple.curveEccN $ Simple.curveParameters prx++ecScalarAdd :: forall curve . Simple.Curve curve+            => Simple.Scalar curve -> Simple.Scalar curve -> Simple.Scalar curve+ecScalarAdd (Simple.Scalar a) (Simple.Scalar b) = Simple.Scalar ((a + b) `mod` n)+  where n = Simple.curveEccN $ Simple.curveParameters (Proxy :: Proxy curve)++ecScalarMul :: forall curve . Simple.Curve curve+            => Simple.Scalar curve -> Simple.Scalar curve -> Simple.Scalar curve+ecScalarMul (Simple.Scalar a) (Simple.Scalar b) = Simple.Scalar ((a * b) `mod` n)+  where n = Simple.curveEccN $ Simple.curveParameters (Proxy :: Proxy curve)
Crypto/MAC/CMAC.hs view
@@ -94,7 +94,7 @@   cipherIPT :: BlockCipher k => k -> [Word8]-cipherIPT = expandIPT . blockSize   where+cipherIPT = expandIPT . blockSize  -- Data type which represents the smallest irreducibule binary polynomial -- against specified degree.
Crypto/Number/F2m.hs view
@@ -16,7 +16,9 @@     , mulF2m     , squareF2m'     , squareF2m+    , powF2m     , modF2m+    , sqrtF2m     , invF2m     , divF2m     ) where@@ -66,8 +68,8 @@ mulF2m fx n1 n2     |    fx < 0       || n1 < 0-      || n2 < 0 = error "mulF2m: negative number represent no binary binary polynomial"-    | fx == 0   = error "modF2m: cannot multiply modulo zero polynomial"+      || n2 < 0 = error "mulF2m: negative number represent no binary polynomial"+    | fx == 0   = error "mulF2m: cannot multiply modulo zero polynomial"     | otherwise = modF2m fx $ go (if n2 `mod` 2 == 1 then n1 else 0) (log2 n2)       where         go n s | s == 0  = n@@ -96,9 +98,36 @@ squareF2m' :: Integer            -> Integer squareF2m' n-    | n < 0     = error "mulF2m: negative number represent no binary binary polynomial"+    | n < 0     = error "mulF2m: negative number represent no binary polynomial"     | otherwise = foldl' (\acc s -> if testBit n s then setBit acc (2 * s) else acc) 0 [0 .. log2 n] {-# INLINE squareF2m' #-}++-- | 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 -- ^Modulus+       -> Integer          -- ^a+       -> Integer          -- ^b+       -> Integer+powF2m fx a b+  | b < 0     = error "powF2m: negative exponents disallowed"+  | b == 0    = if fx > 1 then 1 else 0+  | even b    = squareF2m fx x+  | otherwise = mulF2m fx a (squareF2m' x)+  where x = powF2m fx a (b `div` 2)++-- | 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 -- ^Modulus+        -> Integer          -- ^a+        -> Integer+sqrtF2m fx a = go (log2 fx - 1) a+  where go 0 x = x+        go n x = go (n - 1) (squareF2m fx x)  -- | Extended GCD algorithm for polynomials. For @a@ and @b@ returns @(g, u, v)@ such that @a * u + b * v == g@. --
Crypto/Number/ModArithmetic.hs view
@@ -1,5 +1,4 @@ {-# LANGUAGE BangPatterns #-}-{-# LANGUAGE DeriveDataTypeable #-} -- | -- Module      : Crypto.Number.ModArithmetic -- License     : BSD-style@@ -15,7 +14,10 @@     -- * Inverse computing     , inverse     , inverseCoprimes+    , inverseFermat+    -- * Squares     , jacobi+    , squareRoot     ) where  import Control.Exception (throw, Exception)@@ -56,7 +58,7 @@ -- hiding parameters. -- -- Use this function when all the parameters are public,--- otherwise 'expSafe' should be prefered.+-- otherwise 'expSafe' should be preferred. expFast :: Integer -- ^ base         -> Integer -- ^ exponent         -> Integer -- ^ modulo@@ -70,7 +72,7 @@     | b == 1    = b     | e == 0    = 1     | e == 1    = b `mod` m-    | even e    = let p = (exponentiation b (e `div` 2) m) `mod` m+    | even e    = let p = exponentiation b (e `div` 2) m `mod` m                    in (p^(2::Integer)) `mod` m     | otherwise = (b * exponentiation b (e-1) m) `mod` m @@ -97,17 +99,17 @@  -- | 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 jacobi a n     | n < 3 || even n  = Nothing     | a == 0 || a == 1 = Just a-    | n <= a           = jacobi (a `mod` n) n       -    | a < 0            = +    | n <= a           = jacobi (a `mod` n) n+    | a < 0            =       let b = if n `mod` 4 == 1 then 1 else -1        in fmap (*b) (jacobi (-a) n)     | otherwise        =@@ -120,3 +122,96 @@           n1      = n `mod` a1        in if a1 == 1 then Just s           else fmap (*s) (jacobi n1 a1)++-- | Modular inverse using Fermat's little theorem.  This works only when+-- the modulus is prime but avoids side channels like in 'expSafe'.+inverseFermat :: Integer -> Integer -> Integer+inverseFermat g p = expSafe g (p - 2) p++-- | Raised when the assumption about the modulus is invalid.+data ModulusAssertionError = ModulusAssertionError+    deriving (Show)++instance Exception ModulusAssertionError++-- | 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+squareRoot p+    | p < 2     = throw ModulusAssertionError+    | otherwise =+        case p `divMod` 8 of+           (v, 3) -> method1 (2 * v + 1)+           (v, 7) -> method1 (2 * v + 2)+           (u, 5) -> method2 u+           (_, 1) -> tonelliShanks p+           (0, 2) -> \a -> Just (if even a then 0 else 1)+           _      -> throw ModulusAssertionError++  where+    x `eqMod` y = (x - y) `mod` p == 0++    validate g y | (y * y) `eqMod` g = Just y+                 | otherwise         = Nothing++    -- p == 4u + 3 and u' == u + 1+    method1 u' g =+        let y = expFast g u' p+         in validate g y++    -- p == 8u + 5+    method2 u g =+        let gamma = expFast (2 * g) u p+            g_gamma = g * gamma+            i = (2 * g_gamma * gamma) `mod` p+            y = (g_gamma * (i - 1)) `mod` p+         in validate g y++tonelliShanks :: Integer -> Integer -> Maybe Integer+tonelliShanks p a+    | aa == 0   = Just 0+    | otherwise =+        case expFast aa p2 p of+            b | b == p1   -> Nothing+              | b == 1    -> Just $ go (expFast aa ((s + 1) `div` 2) p)+                                       (expFast aa s p)+                                       (expFast n  s p)+                                       e+              | otherwise -> throw ModulusAssertionError+  where+    aa = a `mod` p+    p1 = p - 1+    p2 = p1 `div` 2+    n  = findN 2++    x `mul` y = (x * y) `mod` p++    pow2m 0 x = x+    pow2m i x = pow2m (i - 1) (x `mul` x)++    (e, s) = asPowerOf2AndOdd p1++    -- find a quadratic non-residue+    findN i+        | expFast i p2 p == p1 = i+        | otherwise            = findN (i + 1)++    -- find m such that b^(2^m) == 1 (mod p)+    findM b i+        | b == 1    = i+        | otherwise = findM (b `mul` b) (i + 1)++    go !x b g !r+        | b == 1    = x+        | otherwise =+            let r' = findM b 0+                z = pow2m (r - r' - 1) g+                x' = x `mul` z+                b' = b `mul` g'+                g' = z `mul` z+             in go x' b' g' r'
Crypto/Number/Prime.hs view
@@ -127,7 +127,7 @@     factorise :: Integer -> Integer -> (Integer, Integer)     factorise !si !vi         | vi `testBit` 0 = (si, vi)-        | otherwise     = factorise (si+1) (vi `shiftR` 1) -- probably faster to not shift v continously, but just once.+        | otherwise     = factorise (si+1) (vi `shiftR` 1) -- probably faster to not shift v continuously, but just once.     expmod = expSafe      -- when iteration reach zero, we have a probable prime
Crypto/PubKey/ECC/P256.hs view
@@ -8,7 +8,6 @@ -- P256 support -- {-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE BangPatterns #-} {-# LANGUAGE EmptyDataDecls #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} module Crypto.PubKey.ECC.P256@@ -22,7 +21,9 @@     , pointDh     , pointsMulVarTime     , pointIsValid+    , pointIsAtInfinity     , toPoint+    , pointX     , pointToIntegers     , pointFromIntegers     , pointToBinary@@ -31,10 +32,13 @@     -- * Scalar arithmetic     , scalarGenerate     , scalarZero+    , scalarN     , scalarIsZero     , scalarAdd     , scalarSub+    , scalarMul     , scalarInv+    , scalarInvSafe     , scalarCmp     , scalarFromBinary     , scalarToBinary@@ -76,6 +80,9 @@ data P256Y data P256X +order :: Integer+order = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551+ ------------------------------------------------------------------------ -- Point methods ------------------------------------------------------------------------@@ -109,7 +116,7 @@ -- | Negate a point pointNegate :: Point -> Point pointNegate a = withNewPoint $ \dx dy ->-    withPoint a $ \ax ay -> do+    withPoint a $ \ax ay ->         ccryptonite_p256e_point_negate ax ay dx dy  -- | Multiply a point by a scalar@@ -117,16 +124,16 @@ -- warning: variable time pointMul :: Scalar -> Point -> Point pointMul scalar p = withNewPoint $ \dx dy ->-    withScalar scalar $ \n -> withPoint p $ \px py -> withScalarZero $ \nzero ->-        ccryptonite_p256_points_mul_vartime nzero n px py dx dy+    withScalar scalar $ \n -> withPoint p $ \px py ->+        ccryptonite_p256e_point_mul n px py dx dy  -- | 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 pointDh scalar p =     B.unsafeCreate scalarSize $ \dst -> withTempPoint $ \dx dy -> do-        withScalar scalar $ \n -> withPoint p $ \px py -> withScalarZero $ \nzero ->-            ccryptonite_p256_points_mul_vartime nzero n px py dx dy+        withScalar scalar $ \n -> withPoint p $ \px py ->+            ccryptonite_p256e_point_mul n px py dx dy         ccryptonite_p256_to_bin (castPtr dx) dst  -- | multiply the point @p with @n2 and add a lifted to curve value @n1@@ -145,6 +152,19 @@     r <- ccryptonite_p256_is_valid_point px py     return (r /= 0) +-- | Check if a 'Point' is the point at infinity+pointIsAtInfinity :: Point -> Bool+pointIsAtInfinity (Point b) = constAllZero b++-- | Return the x coordinate as a 'Scalar' if the point is not at infinity+pointX :: Point -> Maybe Scalar+pointX p+    | pointIsAtInfinity p = Nothing+    | otherwise           = Just $+        withNewScalarFreeze $ \d    ->+        withPoint p         $ \px _ ->+            ccryptonite_p256_mod ccryptonite_SECP256r1_n (castPtr px) (castPtr d)+ -- | Convert a point to (x,y) Integers pointToIntegers :: Point -> (Integer, Integer) pointToIntegers p = unsafeDoIO $ withPoint p $ \px py ->@@ -187,12 +207,12 @@     validatePoint :: Point -> CryptoFailable Point     validatePoint p         | pointIsValid p = CryptoPassed p-        | otherwise      = CryptoFailed $ CryptoError_PointCoordinatesInvalid+        | otherwise      = CryptoFailed CryptoError_PointCoordinatesInvalid  -- | Convert from binary to a point, possibly invalid unsafePointFromBinary :: ByteArrayAccess ba => ba -> CryptoFailable Point unsafePointFromBinary ba-    | B.length ba /= pointSize = CryptoFailed $ CryptoError_PublicKeySizeInvalid+    | B.length ba /= pointSize = CryptoFailed CryptoError_PublicKeySizeInvalid     | otherwise                =         CryptoPassed $ withNewPoint $ \px py -> B.withByteArray ba $ \src -> do             ccryptonite_p256_from_bin src                        (castPtr px)@@ -215,6 +235,10 @@ scalarZero :: Scalar scalarZero = withNewScalarFreeze $ \d -> ccryptonite_p256_init d +-- | The scalar representing the curve order+scalarN :: Scalar+scalarN = throwCryptoError (scalarFromInteger order)+ -- | Check if the scalar is 0 scalarIsZero :: Scalar -> Bool scalarIsZero s = unsafeDoIO $ withScalar s $ \d -> do@@ -237,6 +261,14 @@     withNewScalarFreeze $ \d -> withScalar a $ \pa -> withScalar b $ \pb ->         ccryptonite_p256e_modsub ccryptonite_SECP256r1_n pa pb d +-- | Perform multiplication between two scalars+--+-- > a * b+scalarMul :: Scalar -> Scalar -> Scalar+scalarMul a b =+    withNewScalarFreeze $ \d -> withScalar a $ \pa -> withScalar b $ \pb ->+         ccryptonite_p256_modmul ccryptonite_SECP256r1_n pa 0 pb d+ -- | Give the inverse of the scalar -- -- > 1 / a@@ -247,6 +279,14 @@     withNewScalarFreeze $ \b -> withScalar a $ \pa ->         ccryptonite_p256_modinv_vartime ccryptonite_SECP256r1_n pa b +-- | Give the inverse of the scalar using safe exponentiation+--+-- > 1 / a+scalarInvSafe :: Scalar -> Scalar+scalarInvSafe a =+    withNewScalarFreeze $ \b -> withScalar a $ \pa ->+        ccryptonite_p256e_scalar_invert pa b+ -- | Compare 2 Scalar scalarCmp :: Scalar -> Scalar -> Ordering scalarCmp a b = unsafeDoIO $@@ -257,7 +297,7 @@ -- | convert a scalar from binary scalarFromBinary :: ByteArrayAccess ba => ba -> CryptoFailable Scalar scalarFromBinary ba-    | B.length ba /= scalarSize = CryptoFailed $ CryptoError_SecretKeySizeInvalid+    | B.length ba /= scalarSize = CryptoFailed CryptoError_SecretKeySizeInvalid     | otherwise                 =         CryptoPassed $ withNewScalarFreeze $ \p -> B.withByteArray ba $ \b ->             ccryptonite_p256_from_bin b p@@ -298,18 +338,9 @@ withTempPoint :: (Ptr P256X -> Ptr P256Y -> IO a) -> IO a withTempPoint f = allocTempScrubbed pointSize (\p -> let px = castPtr p in f px (pxToPy px)) -withTempScalar :: (Ptr P256Scalar -> IO a) -> IO a-withTempScalar f = allocTempScrubbed scalarSize (f . castPtr)- withScalar :: Scalar -> (Ptr P256Scalar -> IO a) -> IO a withScalar (Scalar d) f = B.withByteArray d f -withScalarZero :: (Ptr P256Scalar -> IO a) -> IO a-withScalarZero f =-    withTempScalar $ \d -> do-        ccryptonite_p256_init d-        f d- allocTemp :: Int -> (Ptr Word8 -> IO a) -> IO a allocTemp n f = ignoreSnd <$> B.allocRet n f   where@@ -350,6 +381,8 @@     ccryptonite_p256_mod :: Ptr P256Scalar -> Ptr P256Scalar -> Ptr P256Scalar -> IO () foreign import ccall "cryptonite_p256_modmul"     ccryptonite_p256_modmul :: Ptr P256Scalar -> Ptr P256Scalar -> P256Digit -> Ptr P256Scalar -> Ptr P256Scalar -> IO ()+foreign import ccall "cryptonite_p256e_scalar_invert"+    ccryptonite_p256e_scalar_invert :: Ptr P256Scalar -> Ptr P256Scalar -> IO () --foreign import ccall "cryptonite_p256_modinv" --    ccryptonite_p256_modinv :: Ptr P256Scalar -> Ptr P256Scalar -> Ptr P256Scalar -> IO () foreign import ccall "cryptonite_p256_modinv_vartime"@@ -369,6 +402,13 @@     ccryptonite_p256e_point_negate :: Ptr P256X -> Ptr P256Y                                    -> Ptr P256X -> Ptr P256Y                                    -> IO ()++-- compute (out_x,out_y) = n * (in_x,in_y)+foreign import ccall "cryptonite_p256e_point_mul"+    ccryptonite_p256e_point_mul :: Ptr P256Scalar -- n+                                -> Ptr P256X -> Ptr P256Y -- in_{x,y}+                                -> Ptr P256X -> Ptr P256Y -- out_{x,y}+                                -> IO ()  -- compute (out_x,out,y) = n1 * G + n2 * (in_x,in_y) foreign import ccall "cryptonite_p256_points_mul_vartime"
+ Crypto/PubKey/ECDSA.hs view
@@ -0,0 +1,272 @@+-- |+-- Module      : Crypto.PubKey.ECDSA+-- License     : BSD-style+-- Maintainer  : Vincent Hanquez <vincent@snarc.org>+-- Stability   : experimental+-- Portability : unknown+--+-- 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.+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}+module Crypto.PubKey.ECDSA+    ( EllipticCurveECDSA (..)+    -- * Public keys+    , PublicKey+    , encodePublic+    , decodePublic+    , toPublic+    -- * Private keys+    , PrivateKey+    , encodePrivate+    , decodePrivate+    -- * Signatures+    , Signature(..)+    , signatureFromIntegers+    , signatureToIntegers+    -- * Generation and verification+    , signWith+    , signDigestWith+    , sign+    , signDigest+    , verify+    , verifyDigest+    ) where++import           Control.Monad++import           Crypto.ECC+import qualified Crypto.ECC.Simple.Types as Simple+import           Crypto.Error+import           Crypto.Hash+import           Crypto.Hash.Types+import           Crypto.Internal.ByteArray (ByteArray, ByteArrayAccess)+import           Crypto.Internal.Imports+import           Crypto.Number.ModArithmetic (inverseFermat)+import qualified Crypto.PubKey.ECC.P256 as P256+import           Crypto.Random.Types++import           Data.Bits+import qualified Data.ByteArray as B+import           Data.Data++import           Foreign.Ptr (Ptr)+import           Foreign.Storable (peekByteOff, pokeByteOff)++-- | Represent a ECDSA signature namely R and S.+data Signature curve = Signature+    { sign_r :: Scalar curve -- ^ ECDSA r+    , sign_s :: Scalar curve -- ^ ECDSA s+    }++deriving instance Eq (Scalar curve) => Eq (Signature curve)+deriving instance Show (Scalar curve) => Show (Signature curve)++instance NFData (Scalar curve) => NFData (Signature curve) where+    rnf (Signature r s) = rnf r `seq` rnf s `seq` ()++-- | ECDSA Public Key.+type PublicKey curve = Point curve++-- | ECDSA Private Key.+type PrivateKey curve = Scalar curve++-- | Elliptic curves with ECDSA capabilities.+class EllipticCurveBasepointArith curve => EllipticCurveECDSA curve where+    -- | Is a scalar in the accepted range for ECDSA+    scalarIsValid :: proxy curve -> Scalar curve -> Bool++    -- | Test whether the scalar is zero+    scalarIsZero :: proxy curve -> Scalar curve -> Bool+    scalarIsZero prx s = s == throwCryptoError (scalarFromInteger prx 0)++    -- | Scalar inversion modulo the curve order+    scalarInv :: proxy curve -> Scalar curve -> Maybe (Scalar curve)++    -- | Return the point X coordinate as a scalar+    pointX :: proxy curve -> Point curve -> Maybe (Scalar curve)++instance EllipticCurveECDSA Curve_P256R1 where+    scalarIsValid _ s = not (P256.scalarIsZero s)+                            && P256.scalarCmp s P256.scalarN == LT++    scalarIsZero _ = P256.scalarIsZero++    scalarInv _ s = let inv = P256.scalarInvSafe s+                     in if P256.scalarIsZero inv then Nothing else Just inv++    pointX _  = P256.pointX++instance EllipticCurveECDSA Curve_P384R1 where+    scalarIsValid _ = ecScalarIsValid (Proxy :: Proxy Simple.SEC_p384r1)++    scalarIsZero _ = ecScalarIsZero++    scalarInv _ = ecScalarInv (Proxy :: Proxy Simple.SEC_p384r1)++    pointX _  = ecPointX (Proxy :: Proxy Simple.SEC_p384r1)++instance EllipticCurveECDSA Curve_P521R1 where+    scalarIsValid _ = ecScalarIsValid (Proxy :: Proxy Simple.SEC_p521r1)++    scalarIsZero _ = ecScalarIsZero++    scalarInv _ = ecScalarInv (Proxy :: Proxy Simple.SEC_p521r1)++    pointX _  = ecPointX (Proxy :: Proxy Simple.SEC_p521r1)+++-- | Create a signature from integers (R, S).+signatureFromIntegers :: EllipticCurveECDSA curve+                      => proxy curve -> (Integer, Integer) -> CryptoFailable (Signature curve)+signatureFromIntegers prx (r, s) =+    liftA2 Signature (scalarFromInteger prx r) (scalarFromInteger prx s)++-- | 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)+signatureToIntegers prx sig =+    (scalarToInteger prx $ sign_r sig, scalarToInteger prx $ sign_s sig)++-- | Encode a public key into binary form, i.e. the uncompressed encoding+-- referenced from <https://tools.ietf.org/html/rfc5480 RFC 5480> section 2.2.+encodePublic :: (EllipticCurve curve, ByteArray bs)+             => proxy curve -> PublicKey curve -> bs+encodePublic = encodePoint++-- | Try to decode the binary form of a public key.+decodePublic :: (EllipticCurve curve, ByteArray bs)+             => proxy curve -> bs -> CryptoFailable (PublicKey curve)+decodePublic = decodePoint++-- | Encode a private key into binary form, i.e. the @privateKey@ field+-- described in <https://tools.ietf.org/html/rfc5915 RFC 5915>.+encodePrivate :: (EllipticCurveECDSA curve, ByteArray bs)+              => proxy curve -> PrivateKey curve -> bs+encodePrivate = encodeScalar++-- | Try to decode the binary form of a private key.+decodePrivate :: (EllipticCurveECDSA curve, ByteArray bs)+              => proxy curve -> bs -> CryptoFailable (PrivateKey curve)+decodePrivate = decodeScalar++-- | Create a public key from a private key.+toPublic :: EllipticCurveECDSA curve+         => proxy curve -> PrivateKey curve -> PublicKey curve+toPublic = pointBaseSmul++-- | 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)+signDigestWith prx k d digest = do+    let z = tHashDigest prx digest+        point = pointBaseSmul prx k+    r <- pointX prx point+    kInv <- scalarInv prx k+    let s = scalarMul prx kInv (scalarAdd prx z (scalarMul prx r d))+    when (scalarIsZero prx r || scalarIsZero prx s) Nothing+    return $ Signature r s++-- | 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)+signWith prx k d hashAlg msg = signDigestWith prx k d (hashWith hashAlg msg)++-- | Sign a digest using hash and private key.+signDigest :: (EllipticCurveECDSA curve, MonadRandom m, HashAlgorithm hash)+           => proxy curve -> PrivateKey curve -> Digest hash -> m (Signature curve)+signDigest prx pk digest = do+    k <- curveGenerateScalar prx+    case signDigestWith prx k pk digest of+        Nothing  -> signDigest prx pk digest+        Just sig -> return sig++-- | 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 prx pk hashAlg msg = signDigest prx pk (hashWith hashAlg msg)++-- | Verify a digest using hash and public key.+verifyDigest :: (EllipticCurveECDSA curve, HashAlgorithm hash)+       => proxy curve -> PublicKey curve -> Signature curve -> Digest hash -> Bool+verifyDigest prx q (Signature r s) digest+    | not (scalarIsValid prx r) = False+    | not (scalarIsValid prx s) = False+    | otherwise = maybe False (r ==) $ do+        w <- scalarInv prx s+        let z  = tHashDigest prx digest+            u1 = scalarMul prx z w+            u2 = scalarMul prx r w+            x  = pointsSmulVarTime prx u1 u2 q+        pointX prx x+    -- Note: precondition q /= PointO is not tested because we assume+    -- point decoding never decodes point at infinity.++-- | 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 prx hashAlg q sig msg = verifyDigest prx q sig (hashWith hashAlg msg)++-- | Truncate a digest based on curve order size.+tHashDigest :: (EllipticCurveECDSA curve, HashAlgorithm hash)+            => proxy curve -> Digest hash -> Scalar curve+tHashDigest prx (Digest digest) = throwCryptoError $ decodeScalar prx encoded+  where m      = curveOrderBits prx+        d      = m - B.length digest * 8+        (n, r) = m `divMod` 8+        n'     = if r > 0 then succ n else n++        encoded+            | d >  0    = B.zero (n' - B.length digest) `B.append` digest+            | d == 0    = digest+            | r == 0    = B.take n digest+            | otherwise = shiftBytes digest++        shiftBytes bs = B.allocAndFreeze n' $ \dst ->+            B.withByteArray bs $ \src -> go dst src 0 0++        go :: Ptr Word8 -> Ptr Word8 -> Word8 -> Int -> IO ()+        go dst src !a i+            | i >= n'   = return ()+            | otherwise = do+                b <- peekByteOff src i+                pokeByteOff dst i (unsafeShiftR b (8 - r) .|. unsafeShiftL a r)+                go dst src b (succ i)+++ecScalarIsValid :: Simple.Curve c => proxy c -> Simple.Scalar c -> Bool+ecScalarIsValid prx (Simple.Scalar s) = s > 0 && s < n+  where n = Simple.curveEccN $ Simple.curveParameters prx++ecScalarIsZero :: forall curve . Simple.Curve curve+               => Simple.Scalar curve -> Bool+ecScalarIsZero (Simple.Scalar a) = a == 0++ecScalarInv :: Simple.Curve c+            => proxy c -> Simple.Scalar c -> Maybe (Simple.Scalar c)+ecScalarInv prx (Simple.Scalar s)+    | i == 0    = Nothing+    | otherwise = Just $ Simple.Scalar i+  where n = Simple.curveEccN $ Simple.curveParameters prx+        i = inverseFermat s n++ecPointX :: Simple.Curve c+         => proxy c -> Simple.Point c -> Maybe (Simple.Scalar c)+ecPointX _   Simple.PointO      = Nothing+ecPointX prx (Simple.Point x _) = Just (Simple.Scalar $ x `mod` n)+  where n = Simple.curveEccN $ Simple.curveParameters prx
Crypto/Random.hs view
@@ -80,6 +80,10 @@ -- -- 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 drgNewTest = initializeWords 
Crypto/Random/Types.hs view
@@ -17,7 +17,7 @@ import Crypto.Internal.ByteArray  -- | A monad constraint that allows to generate random bytes-class (Functor m, Monad m) => MonadRandom m where+class Monad m => MonadRandom m where     getRandomBytes :: ByteArray byteArray => Int -> m byteArray  -- | A Deterministic Random Generator (DRG) class
+ Crypto/System/CPU.hs view
@@ -0,0 +1,64 @@+-- |+-- Module      : Crypto.System.CPU+-- License     : BSD-style+-- Maintainer  : Olivier Chéron <olivier.cheron@gmail.com>+-- Stability   : experimental+-- Portability : unknown+--+-- Gives information about cryptonite runtime environment.+--+{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE ForeignFunctionInterface #-}+module Crypto.System.CPU+    ( ProcessorOption (..)+    , processorOptions+    ) where++import Data.Data+import Data.List (findIndices)+#ifdef SUPPORT_RDRAND+import Data.Maybe (isJust)+#endif+import Data.Word (Word8)+import Foreign.Ptr+import Foreign.Storable++import Crypto.Internal.Compat++#ifdef SUPPORT_RDRAND+import Crypto.Random.Entropy.RDRand+import Crypto.Random.Entropy.Source+#endif++-- | CPU options impacting cryptography implementation and library performance.+data ProcessorOption+    = AESNI   -- ^ Support for AES instructions, with flag @support_aesni@+    | PCLMUL  -- ^ Support for CLMUL instructions, with flag @support_pclmuldq@+    | RDRAND  -- ^ Support for RDRAND instruction, with flag @support_rdrand@+    deriving (Show,Eq,Enum,Data)++-- | Options which have been enabled at compile time and are supported by the+-- current CPU.+processorOptions :: [ProcessorOption]+processorOptions = unsafeDoIO $ do+    p <- cryptonite_aes_cpu_init+    options <- traverse (getOption p) aesOptions+    rdrand  <- hasRDRand+    return (decodeOptions options ++ [ RDRAND | rdrand ])+  where+    aesOptions    = [ AESNI .. PCLMUL ]+    getOption p   = peekElemOff p . fromEnum+    decodeOptions = map toEnum . findIndices (> 0)+{-# NOINLINE processorOptions #-}++hasRDRand :: IO Bool+#ifdef SUPPORT_RDRAND+hasRDRand = fmap isJust getRDRand+  where getRDRand = entropyOpen :: IO (Maybe RDRand)+#else+hasRDRand = return False+#endif++foreign import ccall unsafe "cryptonite_aes_cpu_init"+    cryptonite_aes_cpu_init :: IO (Ptr Word8)
Crypto/Tutorial.hs view
@@ -8,6 +8,9 @@        -- * Symmetric block ciphers       -- $symmetric_block_ciphers++      -- * Combining primitives+      -- $combining_primitives     ) where  -- $api_design@@ -147,3 +150,46 @@ -- >           putStrLn $ "Original Message: " ++ show msg -- >           putStrLn $ "Message after encryption: " ++ show eMsg -- >           putStrLn $ "Message after decryption: " ++ show dMsg++-- $combining_primitives+--+-- This example shows how to use Curve25519, XSalsa and Poly1305 primitives to+-- emulate NaCl's @crypto_box@ construct.+--+-- > import qualified Data.ByteArray as BA+-- > import           Data.ByteString (ByteString)+-- > import qualified Data.ByteString as B+-- >+-- > import qualified Crypto.Cipher.XSalsa as XSalsa+-- > import qualified Crypto.MAC.Poly1305 as Poly1305+-- > import qualified Crypto.PubKey.Curve25519 as X25519+-- >+-- > -- | Build a @crypto_box@ packet encrypting the specified content with a+-- > -- 192-bit nonce, receiver public key and sender private key.+-- > crypto_box content nonce pk sk = BA.convert tag `B.append` c+-- >   where+-- >     zero         = B.replicate 16 0+-- >     shared       = X25519.dh pk sk+-- >     (iv0, iv1)   = B.splitAt 8 nonce+-- >     state0       = XSalsa.initialize 20 shared (zero `B.append` iv0)+-- >     state1       = XSalsa.derive state0 iv1+-- >     (rs, state2) = XSalsa.generate state1 32+-- >     (c, _)       = XSalsa.combine state2 content+-- >     tag          = Poly1305.auth (rs :: ByteString) c+-- >+-- > -- | Try to open a @crypto_box@ packet and recover the content using the+-- > -- 192-bit nonce, sender public key and receiver private key.+-- > crypto_box_open packet nonce pk sk+-- >     | B.length packet < 16 = Nothing+-- >     | BA.constEq tag' tag  = Just content+-- >     | otherwise            = Nothing+-- >   where+-- >     (tag', c)    = B.splitAt 16 packet+-- >     zero         = B.replicate 16 0+-- >     shared       = X25519.dh pk sk+-- >     (iv0, iv1)   = B.splitAt 8 nonce+-- >     state0       = XSalsa.initialize 20 shared (zero `B.append` iv0)+-- >     state1       = XSalsa.derive state0 iv1+-- >     (rs, state2) = XSalsa.generate state1 32+-- >     (content, _) = XSalsa.combine state2 c+-- >     tag          = Poly1305.auth (rs :: ByteString) c
benchs/Bench.hs view
@@ -6,6 +6,7 @@ import Gauge.Main  import           Crypto.Cipher.AES+import qualified Crypto.Cipher.AESGCMSIV as AESGCMSIV import           Crypto.Cipher.Blowfish import           Crypto.Cipher.CAST5 import qualified Crypto.Cipher.ChaChaPoly1305 as CP@@ -22,12 +23,15 @@ import qualified Crypto.PubKey.DH as DH import qualified Crypto.PubKey.ECC.Types as ECC import qualified Crypto.PubKey.ECC.Prim as ECC+import qualified Crypto.PubKey.ECDSA as ECDSA import           Crypto.Random  import           Control.DeepSeq (NFData) import           Data.ByteArray (ByteArray, Bytes) import qualified Data.ByteString as B +import qualified Crypto.PubKey.ECC.P256 as P256+ import Number.F2m  data HashAlg = forall alg . HashAlgorithm alg => HashAlg alg@@ -123,7 +127,7 @@     [ bgroup "ECB" benchECB     , bgroup "CBC" benchCBC     ]-  where +  where         benchECB =             [ bench "DES-input=1024" $ nf (run (undefined :: DES) cipherInit key8) input1024             , bench "Blowfish128-input=1024" $ nf (run (undefined :: Blowfish128) cipherInit key16) input1024@@ -165,6 +169,7 @@     [ bench "ChaChaPoly1305" $ nf (cp key32) (input64, input1024)     , bench "AES-GCM" $ nf (gcm key32) (input64, input1024)     , bench "AES-CCM" $ nf (ccm key32) (input64, input1024)+    , bench "AES-GCM-SIV" $ nf (gcmsiv key32) (input64, input1024)     ]   where cp k (ini, plain) =             let iniState            = throwCryptoError $ CP.initialize k (throwCryptoError $ CP.nonce12 nonce12)@@ -184,6 +189,11 @@                 state = throwCryptoError $ aeadInit mode ctx nonce12              in aeadSimpleEncrypt state ini plain 16 +        gcmsiv k (ini, plain) =+            let ctx = throwCryptoError (cipherInit k) :: AES256+                iv = throwCryptoError (AESGCMSIV.nonce nonce12)+             in AESGCMSIV.encrypt ctx iv ini plain+         input64 = B.replicate 64 0         input1024 = B.replicate 1024 0 @@ -195,20 +205,42 @@ benchECC =     [ bench "pointAddTwoMuls-baseline"  $ nf run_b (n1, p1, n2, p2)     , bench "pointAddTwoMuls-optimized" $ nf run_o (n1, p1, n2, p2)+    , bench "pointAdd-ECC" $ nf run_c (p1, p2)+    , bench "pointMul-ECC" $ nf run_d (n1, p2)     ]   where run_b (n, p, k, q) = ECC.pointAdd c (ECC.pointMul c n p)                                             (ECC.pointMul c k q)          run_o (n, p, k, q) = ECC.pointAddTwoMuls c n p k q+        run_c (p, q) = ECC.pointAdd c p q+        run_d (n, p) = ECC.pointMul c n p          c  = ECC.getCurveByName ECC.SEC_p256r1-        r1 = 7-        r2 = 11-        p1 = ECC.pointBaseMul c r1-        p2 = ECC.pointBaseMul c r2+        p1 = ECC.pointBaseMul c n1+        p2 = ECC.pointBaseMul c n2         n1 = 0x2ba9daf2363b2819e69b34a39cf496c2458a9b2a21505ea9e7b7cbca42dc7435         n2 = 0xf054a7f60d10b8c2cf847ee90e9e029f8b0e971b09ca5f55c4d49921a11fadc1 +benchP256 =+    [ bench "pointAddTwoMuls-P256"  $ nf run_p (n1, p1, n2, p2)+    , bench "pointAdd-P256"  $ nf run_q (p1, p2)+    , bench "pointMul-P256"  $ nf run_t (n1, p1)+    ]+  where run_p (n, p, k, q) = P256.pointAdd (P256.pointMul n p) (P256.pointMul k q)+        run_q (p, q) = P256.pointAdd p q+        run_t (n, p) = P256.pointMul n p++        xS = 0xde2444bebc8d36e682edd27e0f271508617519b3221a8fa0b77cab3989da97c9+        yS = 0xc093ae7ff36e5380fc01a5aad1e66659702de80f53cec576b6350b243042a256+        xT = 0x55a8b00f8da1d44e62f6b3b25316212e39540dc861c89575bb8cf92e35e0986b+        yT = 0x5421c3209c2d6c704835d82ac4c3dd90f61a8a52598b9e7ab656e9d8c8b24316+        p1 = P256.pointFromIntegers (xS, yS)+        p2 = P256.pointFromIntegers (xT, yT)+        n1 = throwCryptoError $ P256.scalarFromInteger 0x2ba9daf2363b2819e69b34a39cf496c2458a9b2a21505ea9e7b7cbca42dc7435+        n2 = throwCryptoError $ P256.scalarFromInteger 0xf054a7f60d10b8c2cf847ee90e9e029f8b0e971b09ca5f55c4d49921a11fadc1+++ benchFFDH = map doFFDHBench primes   where     doFFDHBench (e, p) =@@ -255,6 +287,44 @@              , ("X448",   CurveDH Curve_X448)              ] +data CurveHashECDSA =+    forall curve hashAlg . (ECDSA.EllipticCurveECDSA curve,+                            NFData (Scalar curve),+                            NFData (Point curve),+                            HashAlgorithm hashAlg) => CurveHashECDSA curve hashAlg++benchECDSA = map doECDSABench curveHashes+  where+    doECDSABench (name, CurveHashECDSA c hashAlg) =+        let proxy = Just c -- using Maybe as Proxy+         in bgroup name+                [ env (signGenerate proxy) $ bench "sign" . nfIO . signRun proxy hashAlg+                , env (verifyGenerate proxy hashAlg) $ bench "verify" . nf (verifyRun proxy hashAlg)+                ]++    signGenerate proxy = do+        m <- tenKB+        s <- curveGenerateScalar proxy+        return (s, m)++    signRun proxy hashAlg (priv, msg) = ECDSA.sign proxy priv hashAlg msg++    verifyGenerate proxy hashAlg = do+        m <- tenKB+        KeyPair p s <- curveGenerateKeyPair proxy+        sig <- ECDSA.sign proxy s hashAlg m+        return (p, sig, m)++    verifyRun proxy hashAlg (pub, sig, msg) = ECDSA.verify proxy hashAlg pub sig msg++    tenKB :: IO Bytes+    tenKB = getRandomBytes 10240++    curveHashes = [ ("secp256r1_sha256", CurveHashECDSA Curve_P256R1 SHA256)+                  , ("secp384r1_sha384", CurveHashECDSA Curve_P384R1 SHA384)+                  , ("secp521r1_sha512", CurveHashECDSA Curve_P521R1 SHA512)+                  ]+ main = defaultMain     [ bgroup "hash" benchHash     , bgroup "block-cipher" benchBlockCipher@@ -262,9 +332,11 @@     , bgroup "pbkdf2" benchPBKDF2     , bgroup "bcrypt" benchBCrypt     , bgroup "ECC" benchECC+    , bgroup "P256" benchP256     , bgroup "DH"           [ bgroup "FFDH" benchFFDH           , bgroup "ECDH" benchECDH           ]+    , bgroup "ECDSA" benchECDSA     , bgroup "F2m" benchF2m     ]
cbits/aes/block128.h view
@@ -108,6 +108,13 @@ 	} } +static inline void block128_byte_reverse(block128 *a)+{+	uint64_t s0 = a->q[0], s1 = a->q[1];+	a->q[0] = bitfn_swap64(s1);+	a->q[1] = bitfn_swap64(s0);+}+ static inline void block128_inc_be(block128 *b) { 	uint64_t v = be64_to_cpu(b->q[1]);@@ -116,6 +123,16 @@ 		b->q[1] = 0; 	} else 		b->q[1] = cpu_to_be64(v);+}++static inline void block128_inc32_be(block128 *b)+{+	b->d[3] = cpu_to_be32(be32_to_cpu(b->d[3]) + 1);+}++static inline void block128_inc32_le(block128 *b)+{+	b->d[0] = cpu_to_le32(le32_to_cpu(b->d[0]) + 1); }  #ifdef IMPL_DEBUG
cbits/aes/gf.c view
@@ -34,39 +34,113 @@ #include <aes/gf.h> #include <aes/x86ni.h> -/* this is a really inefficient way to GF multiply.- * the alternative without hw accel is building small tables- * to speed up the multiplication.- * TODO: optimise with tables+/* inplace GFMUL for xts mode */+void cryptonite_aes_generic_gf_mulx(block128 *a)+{+	const uint64_t gf_mask = cpu_to_le64(0x8000000000000000ULL);+	uint64_t r = ((a->q[1] & gf_mask) ? cpu_to_le64(0x87) : 0);+	a->q[1] = cpu_to_le64((le64_to_cpu(a->q[1]) << 1) | (a->q[0] & gf_mask ? 1 : 0));+	a->q[0] = cpu_to_le64(le64_to_cpu(a->q[0]) << 1) ^ r;+}+++/*+ * GF multiplication with Shoup's method and 4-bit table.+ *+ * We precompute the products of H with all 4-bit polynomials and store them in+ * a 'table_4bit' array.  To avoid unnecessary byte swapping, the 16 blocks are+ * written to the table with qwords already converted to CPU order.  Table+ * indices use the reflected bit ordering, i.e. polynomials X^0, X^1, X^2, X^3+ * map to bit positions 3, 2, 1, 0 respectively.+ *+ * To multiply an arbitrary block with H, the input block is decomposed in 4-bit+ * segments.  We get the final result after 32 table lookups and additions, one+ * for each segment, interleaving multiplication by P(X)=X^4.  */-void cryptonite_aes_generic_gf_mul(block128 *a, block128 *b)++/* convert block128 qwords between BE and CPU order */+static inline void block128_cpu_swap_be(block128 *a, const block128 *b) {-	uint64_t a0, a1, v0, v1;+	a->q[1] = cpu_to_be64(b->q[1]);+	a->q[0] = cpu_to_be64(b->q[0]);+}++/* multiplication by P(X)=X, assuming qwords already in CPU order */+static inline void cpu_gf_mulx(block128 *a, const block128 *b)+{+	uint64_t v0 = b->q[0];+	uint64_t v1 = b->q[1];+	a->q[1] = v1 >> 1 | v0 << 63;+	a->q[0] = v0 >> 1 ^ ((0-(v1 & 1)) & 0xe100000000000000ULL);+}++static const uint64_t r4_0[] =+	{ 0x0000000000000000ULL, 0x1c20000000000000ULL+	, 0x3840000000000000ULL, 0x2460000000000000ULL+	, 0x7080000000000000ULL, 0x6ca0000000000000ULL+	, 0x48c0000000000000ULL, 0x54e0000000000000ULL+	, 0xe100000000000000ULL, 0xfd20000000000000ULL+	, 0xd940000000000000ULL, 0xc560000000000000ULL+	, 0x9180000000000000ULL, 0x8da0000000000000ULL+	, 0xa9c0000000000000ULL, 0xb5e0000000000000ULL+	};++/* multiplication by P(X)=X^4, assuming qwords already in CPU order */+static inline void cpu_gf_mulx4(block128 *a, const block128 *b)+{+	uint64_t v0 = b->q[0];+	uint64_t v1 = b->q[1];+	a->q[1] = v1 >> 4 | v0 << 60;+	a->q[0] = v0 >> 4 ^ r4_0[v1 & 0xf];+}++/* initialize the 4-bit table given H */+void cryptonite_aes_generic_hinit(table_4bit htable, const block128 *h)+{+	block128 v, *p; 	int i, j; -	a0 = a1 = 0;-	v0 = cpu_to_be64(a->q[0]);-	v1 = cpu_to_be64(a->q[1]);+	/* multiplication by 0 is 0 */+	block128_zero(&htable[0]); -	for (i = 0; i < 16; i++)-		for (j = 0x80; j != 0; j >>= 1) {-			uint8_t x = b->b[i] & j;-			a0 ^= x ? v0 : 0;-			a1 ^= x ? v1 : 0;-			x = (uint8_t) v1 & 1;-			v1 = (v1 >> 1) | (v0 << 63);-			v0 = (v0 >> 1) ^ (x ? (0xe1ULL << 56) : 0);+	/* at index 8=2^3 we have H.X^0 = H */+	i = 8;+	block128_cpu_swap_be(&htable[i], h); /* in CPU order */+	p = &htable[i];++	/* for other powers of 2, repeat multiplication by P(X)=X */+	for (i = 4; i > 0; i >>= 1)+	{+		cpu_gf_mulx(&htable[i], p);+		p = &htable[i];+	}++	/* remaining elements are linear combinations */+	for (i = 2; i < 16; i <<= 1) {+		p = &htable[i];+		v = *p;+		for (j = 1; j < i; j++) {+			p[j] = v;+			block128_xor_aligned(&p[j], &htable[j]); 		}-	a->q[0] = cpu_to_be64(a0);-	a->q[1] = cpu_to_be64(a1);+	} } -/* inplace GFMUL for xts mode */-void cryptonite_aes_generic_gf_mulx(block128 *a)+/* multiply a block with H */+void cryptonite_aes_generic_gf_mul(block128 *a, const table_4bit htable) {-	const uint64_t gf_mask = cpu_to_le64(0x8000000000000000ULL);-	uint64_t r = ((a->q[1] & gf_mask) ? cpu_to_le64(0x87) : 0);-	a->q[1] = cpu_to_le64((le64_to_cpu(a->q[1]) << 1) | (a->q[0] & gf_mask ? 1 : 0));-	a->q[0] = cpu_to_le64(le64_to_cpu(a->q[0]) << 1) ^ r;+	block128 b;+	int i;+	block128_zero(&b);+	for (i = 15; i >= 0; i--)+	{+		uint8_t v = a->b[i];+		block128_xor_aligned(&b, &htable[v & 0xf]); /* high bits (reflected) */+		cpu_gf_mulx4(&b, &b);+		block128_xor_aligned(&b, &htable[v >> 4]);  /* low bits (reflected) */+		if (i > 0)+			cpu_gf_mulx4(&b, &b);+		else+			block128_cpu_swap_be(a, &b); /* restore BE order when done */+	} }-
cbits/aes/gf.h view
@@ -32,7 +32,11 @@  #include "aes/block128.h" -void cryptonite_aes_generic_gf_mul(block128 *a, block128 *b);+typedef block128 table_4bit[16];+ void cryptonite_aes_generic_gf_mulx(block128 *a);++void cryptonite_aes_generic_hinit(table_4bit htable, const block128 *h);+void cryptonite_aes_generic_gf_mul(block128 *a, const table_4bit htable);  #endif
cbits/aes/x86ni.c view
@@ -46,6 +46,7 @@ /* old GCC version doesn't cope with the shuffle parameters, that can take 2 values (0xff and 0xaa)  * in our case, passed as argument despite being a immediate 8 bits constant anyway.  * un-factorise aes_128_key_expansion into 2 version that have the shuffle parameter explicitly set */+TARGET_AESNI static __m128i aes_128_key_expansion_ff(__m128i key, __m128i keygened) { 	keygened = _mm_shuffle_epi32(keygened, 0xff);@@ -55,6 +56,7 @@ 	return _mm_xor_si128(key, keygened); } +TARGET_AESNI static __m128i aes_128_key_expansion_aa(__m128i key, __m128i keygened) { 	keygened = _mm_shuffle_epi32(keygened, 0xaa);@@ -64,6 +66,7 @@ 	return _mm_xor_si128(key, keygened); } +TARGET_AESNI void cryptonite_aesni_init(aes_key *key, uint8_t *ikey, uint8_t size) { 	__m128i k[28];@@ -145,6 +148,7 @@ /* TO OPTIMISE: use pcmulqdq... or some faster code.  * this is the lamest way of doing it, but i'm out of time.  * this is basically a copy of gf_mulx in gf.c */+TARGET_AESNI static __m128i gfmulx(__m128i v) { 	uint64_t v_[2] ALIGNMENT(16);@@ -158,33 +162,34 @@ 	return v; } -static __m128i gfmul_generic(__m128i tag, __m128i h)+TARGET_AESNI+static __m128i gfmul_generic(__m128i tag, const table_4bit htable) {-	aes_block _t, _h;+	aes_block _t; 	_mm_store_si128((__m128i *) &_t, tag);-	_mm_store_si128((__m128i *) &_h, h);-	cryptonite_aes_generic_gf_mul(&_t, &_h);+	cryptonite_aes_generic_gf_mul(&_t, htable); 	tag = _mm_load_si128((__m128i *) &_t); 	return tag; }  #ifdef WITH_PCLMUL -__m128i (*gfmul_branch_ptr)(__m128i a, __m128i b) = gfmul_generic;-#define gfmul(a,b) ((*gfmul_branch_ptr)(a,b))+__m128i (*gfmul_branch_ptr)(__m128i a, const table_4bit t) = gfmul_generic;+#define gfmul(a,t) ((*gfmul_branch_ptr)(a,t))  /* See Intel carry-less-multiplication-instruction-in-gcm-mode-paper.pdf  *  * Adapted from figure 5, with additional byte swapping so that interface  * is simimar to cryptonite_aes_generic_gf_mul.  */-static __m128i gfmul_pclmuldq(__m128i a, __m128i b)+TARGET_AESNI_PCLMUL+static __m128i gfmul_pclmuldq(__m128i a, const table_4bit htable) {-	__m128i tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9;+	__m128i b, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9; 	__m128i bswap_mask = _mm_set_epi8(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);  	a = _mm_shuffle_epi8(a, bswap_mask);-	b = _mm_shuffle_epi8(b, bswap_mask);+	b = _mm_loadu_si128((__m128i *) htable);  	tmp3 = _mm_clmulepi64_si128(a, b, 0x00); 	tmp4 = _mm_clmulepi64_si128(a, b, 0x10);@@ -231,28 +236,39 @@ 	return _mm_shuffle_epi8(tmp6, bswap_mask); } -void cryptonite_aesni_gf_mul(block128 *a, block128 *b)+void cryptonite_aesni_hinit_pclmul(table_4bit htable, const block128 *h) {-	__m128i _a, _b, _c;+	/* When pclmul is active we don't need to fill the table.  Instead we just+	 * store H at index 0.  It is written in reverse order, so function+	 * gfmul_pclmuldq will not byte-swap this value.+	 */+	htable->q[0] = bitfn_swap64(h->q[1]);+	htable->q[1] = bitfn_swap64(h->q[0]);+}++TARGET_AESNI_PCLMUL+void cryptonite_aesni_gf_mul_pclmul(block128 *a, const table_4bit htable)+{+	__m128i _a, _b; 	_a = _mm_loadu_si128((__m128i *) a);-	_b = _mm_loadu_si128((__m128i *) b);-	_c = gfmul_pclmuldq(_a, _b);-	_mm_storeu_si128((__m128i *) a, _c);+	_b = gfmul_pclmuldq(_a, htable);+	_mm_storeu_si128((__m128i *) a, _b); } -void cryptonite_aesni_init_pclmul()+void cryptonite_aesni_init_pclmul(void) { 	gfmul_branch_ptr = gfmul_pclmuldq; }  #else-#define gfmul(a,b) (gfmul_generic(a,b))+#define gfmul(a,t) (gfmul_generic(a,t)) #endif -static inline __m128i ghash_add(__m128i tag, __m128i h, __m128i m)+TARGET_AESNI+static inline __m128i ghash_add(__m128i tag, const table_4bit htable, __m128i m) { 	tag = _mm_xor_si128(tag, m);-	return gfmul(tag, h);+	return gfmul(tag, htable); }  #define PRELOAD_ENC_KEYS128(k) \
cbits/aes/x86ni.h view
@@ -40,7 +40,16 @@ #include <cryptonite_aes.h> #include <aes/block128.h> +#ifdef WITH_TARGET_ATTRIBUTES+#define TARGET_AESNI __attribute__((target("ssse3,aes")))+#define TARGET_AESNI_PCLMUL __attribute__((target("sse4.1,aes,pclmul")))+#else+#define TARGET_AESNI+#define TARGET_AESNI_PCLMUL+#endif+ #ifdef IMPL_DEBUG+TARGET_AESNI static void block128_sse_print(__m128i m) { 	block128 b;@@ -64,6 +73,8 @@ void cryptonite_aesni_decrypt_cbc256(aes_block *out, aes_key *key, aes_block *_iv, aes_block *in, uint32_t blocks); void cryptonite_aesni_encrypt_ctr128(uint8_t *out, aes_key *key, aes_block *_iv, uint8_t *in, uint32_t length); void cryptonite_aesni_encrypt_ctr256(uint8_t *out, aes_key *key, aes_block *_iv, uint8_t *in, uint32_t length);+void cryptonite_aesni_encrypt_c32_128(uint8_t *out, aes_key *key, aes_block *_iv, uint8_t *in, uint32_t length);+void cryptonite_aesni_encrypt_c32_256(uint8_t *out, aes_key *key, aes_block *_iv, uint8_t *in, uint32_t length); void cryptonite_aesni_encrypt_xts128(aes_block *out, aes_key *key1, aes_key *key2,                            aes_block *_tweak, uint32_t spoint, aes_block *in, uint32_t blocks); void cryptonite_aesni_encrypt_xts256(aes_block *out, aes_key *key1, aes_key *key2,@@ -73,8 +84,9 @@ void cryptonite_aesni_gcm_encrypt256(uint8_t *out, aes_gcm *gcm, aes_key *key, uint8_t *in, uint32_t length);  #ifdef WITH_PCLMUL-void cryptonite_aesni_init_pclmul();-void cryptonite_aesni_gf_mul(block128 *a, block128 *b);+void cryptonite_aesni_init_pclmul(void);+void cryptonite_aesni_hinit_pclmul(table_4bit htable, const block128 *h);+void cryptonite_aesni_gf_mul_pclmul(block128 *a, const table_4bit htable); #endif  #endif
cbits/aes/x86ni_impl.c view
@@ -28,6 +28,7 @@  * SUCH DAMAGE.  */ +TARGET_AESNI void SIZED(cryptonite_aesni_encrypt_block)(aes_block *out, aes_key *key, aes_block *in) { 	__m128i *k = (__m128i *) key->data;@@ -37,6 +38,7 @@ 	_mm_storeu_si128((__m128i *) out, m); } +TARGET_AESNI void SIZED(cryptonite_aesni_decrypt_block)(aes_block *out, aes_key *key, aes_block *in) { 	__m128i *k = (__m128i *) key->data;@@ -46,6 +48,7 @@ 	_mm_storeu_si128((__m128i *) out, m); } +TARGET_AESNI void SIZED(cryptonite_aesni_encrypt_ecb)(aes_block *out, aes_key *key, aes_block *in, uint32_t blocks) { 	__m128i *k = (__m128i *) key->data;@@ -58,6 +61,7 @@ 	} } +TARGET_AESNI void SIZED(cryptonite_aesni_decrypt_ecb)(aes_block *out, aes_key *key, aes_block *in, uint32_t blocks) { 	__m128i *k = (__m128i *) key->data;@@ -71,6 +75,7 @@ 	} } +TARGET_AESNI void SIZED(cryptonite_aesni_encrypt_cbc)(aes_block *out, aes_key *key, aes_block *_iv, aes_block *in, uint32_t blocks) { 	__m128i *k = (__m128i *) key->data;@@ -87,6 +92,7 @@ 	} } +TARGET_AESNI void SIZED(cryptonite_aesni_decrypt_cbc)(aes_block *out, aes_key *key, aes_block *_iv, aes_block *in, uint32_t blocks) { 	__m128i *k = (__m128i *) key->data;@@ -106,6 +112,7 @@ 	} } +TARGET_AESNI void SIZED(cryptonite_aesni_encrypt_ctr)(uint8_t *output, aes_key *key, aes_block *_iv, uint8_t *input, uint32_t len) { 	__m128i *k = (__m128i *) key->data;@@ -151,6 +158,49 @@ 	return ; } +TARGET_AESNI+void SIZED(cryptonite_aesni_encrypt_c32_)(uint8_t *output, aes_key *key, aes_block *_iv, uint8_t *input, uint32_t len)+{+	__m128i *k = (__m128i *) key->data;+	__m128i one        = _mm_set_epi32(0,0,0,1);+	uint32_t nb_blocks = len / 16;+	uint32_t part_block_len = len % 16;++	/* get the IV */+	__m128i iv = _mm_loadu_si128((__m128i *) _iv);++	PRELOAD_ENC(k);++	for (; nb_blocks-- > 0; output += 16, input += 16) {+		/* encrypt the iv and and xor it the input block */+		__m128i tmp = iv;+		DO_ENC_BLOCK(tmp);+		__m128i m = _mm_loadu_si128((__m128i *) input);+		m = _mm_xor_si128(m, tmp);++		_mm_storeu_si128((__m128i *) output, m);+		/* iv += 1 */+		iv = _mm_add_epi32(iv, one);+	}++	if (part_block_len != 0) {+		aes_block block;+		memset(&block.b, 0, 16);+		memcpy(&block.b, input, part_block_len);++		__m128i m = _mm_loadu_si128((__m128i *) &block);+		__m128i tmp = iv;++		DO_ENC_BLOCK(tmp);+		m = _mm_xor_si128(m, tmp);+		_mm_storeu_si128((__m128i *) &block.b, m);+		memcpy(output, &block.b, part_block_len);+	}++	return ;+}++TARGET_AESNI void SIZED(cryptonite_aesni_encrypt_xts)(aes_block *out, aes_key *key1, aes_key *key2,                                aes_block *_tweak, uint32_t spoint, aes_block *in, uint32_t blocks) {@@ -181,6 +231,7 @@ 	} while (0); } +TARGET_AESNI void SIZED(cryptonite_aesni_gcm_encrypt)(uint8_t *output, aes_gcm *gcm, aes_key *key, uint8_t *input, uint32_t length) { 	__m128i *k = (__m128i *) key->data;@@ -191,7 +242,6 @@  	gcm->length_input += length; -	__m128i h  = _mm_loadu_si128((__m128i *) &gcm->h); 	__m128i tag = _mm_loadu_si128((__m128i *) &gcm->tag); 	__m128i iv = _mm_loadu_si128((__m128i *) &gcm->civ); 	iv = _mm_shuffle_epi8(iv, bswap_mask);@@ -200,7 +250,7 @@  	for (; nb_blocks-- > 0; output += 16, input += 16) { 		/* iv += 1 */-		iv = _mm_add_epi64(iv, one);+		iv = _mm_add_epi32(iv, one);  		/* put back iv in big endian, encrypt it, 		 * and xor it to input */@@ -209,7 +259,7 @@ 		__m128i m = _mm_loadu_si128((__m128i *) input); 		m = _mm_xor_si128(m, tmp); -		tag = ghash_add(tag, h, m);+		tag = ghash_add(tag, gcm->htable, m);  		/* store it out */ 		_mm_storeu_si128((__m128i *) output, m);@@ -240,7 +290,7 @@ 		block128_copy_bytes(&block, input, part_block_len);  		/* iv += 1 */-		iv = _mm_add_epi64(iv, one);+		iv = _mm_add_epi32(iv, one);  		/* put back iv in big endian mode, encrypt it and xor it with input */ 		__m128i tmp = _mm_shuffle_epi8(iv, bswap_mask);@@ -250,7 +300,7 @@ 		m = _mm_xor_si128(m, tmp); 		m = _mm_shuffle_epi8(m, mask); -		tag = ghash_add(tag, h, m);+		tag = ghash_add(tag, gcm->htable, m);  		/* make output */ 		_mm_storeu_si128((__m128i *) &block.b, m);
cbits/cryptonite_aes.c view
@@ -44,6 +44,7 @@ void cryptonite_aes_generic_encrypt_cbc(aes_block *output, aes_key *key, aes_block *iv, aes_block *input, uint32_t nb_blocks); void cryptonite_aes_generic_decrypt_cbc(aes_block *output, aes_key *key, aes_block *iv, aes_block *input, uint32_t nb_blocks); void cryptonite_aes_generic_encrypt_ctr(uint8_t *output, aes_key *key, aes_block *iv, uint8_t *input, uint32_t length);+void cryptonite_aes_generic_encrypt_c32(uint8_t *output, aes_key *key, aes_block *iv, uint8_t *input, uint32_t length); void cryptonite_aes_generic_encrypt_xts(aes_block *output, aes_key *k1, aes_key *k2, aes_block *dataunit,                              uint32_t spoint, aes_block *input, uint32_t nb_blocks); void cryptonite_aes_generic_decrypt_xts(aes_block *output, aes_key *k1, aes_key *k2, aes_block *dataunit,@@ -69,6 +70,8 @@ 	DECRYPT_CBC_128, DECRYPT_CBC_192, DECRYPT_CBC_256, 	/* ctr */ 	ENCRYPT_CTR_128, ENCRYPT_CTR_192, ENCRYPT_CTR_256,+	/* ctr with 32-bit wrapping */+	ENCRYPT_C32_128, ENCRYPT_C32_192, ENCRYPT_C32_256, 	/* xts */ 	ENCRYPT_XTS_128, ENCRYPT_XTS_192, ENCRYPT_XTS_256, 	DECRYPT_XTS_128, DECRYPT_XTS_192, DECRYPT_XTS_256,@@ -82,7 +85,7 @@ 	ENCRYPT_CCM_128, ENCRYPT_CCM_192, ENCRYPT_CCM_256, 	DECRYPT_CCM_128, DECRYPT_CCM_192, DECRYPT_CCM_256, 	/* ghash */-	GHASH_GF_MUL,+	GHASH_HINIT, GHASH_GF_MUL, };  void *cryptonite_aes_branch_table[] = {@@ -115,6 +118,10 @@ 	[ENCRYPT_CTR_128]   = cryptonite_aes_generic_encrypt_ctr, 	[ENCRYPT_CTR_192]   = cryptonite_aes_generic_encrypt_ctr, 	[ENCRYPT_CTR_256]   = cryptonite_aes_generic_encrypt_ctr,+	/* CTR with 32-bit wrapping */+	[ENCRYPT_C32_128]   = cryptonite_aes_generic_encrypt_c32,+	[ENCRYPT_C32_192]   = cryptonite_aes_generic_encrypt_c32,+	[ENCRYPT_C32_256]   = cryptonite_aes_generic_encrypt_c32, 	/* XTS */ 	[ENCRYPT_XTS_128]   = cryptonite_aes_generic_encrypt_xts, 	[ENCRYPT_XTS_192]   = cryptonite_aes_generic_encrypt_xts,@@ -144,6 +151,7 @@ 	[DECRYPT_CCM_192]   = cryptonite_aes_generic_ccm_decrypt, 	[DECRYPT_CCM_256]   = cryptonite_aes_generic_ccm_decrypt, 	/* GHASH */+	[GHASH_HINIT]       = cryptonite_aes_generic_hinit, 	[GHASH_GF_MUL]      = cryptonite_aes_generic_gf_mul, }; @@ -156,7 +164,8 @@ typedef void (*ocb_crypt_f)(uint8_t *output, aes_ocb *ocb, aes_key *key, uint8_t *input, uint32_t length); typedef void (*ccm_crypt_f)(uint8_t *output, aes_ccm *ccm, aes_key *key, uint8_t *input, uint32_t length); typedef void (*block_f)(aes_block *output, aes_key *key, aes_block *input);-typedef void (*gf_mul_f)(aes_block *a, aes_block *b);+typedef void (*hinit_f)(table_4bit htable, const block128 *h);+typedef void (*gf_mul_f)(block128 *a, const table_4bit htable);  #ifdef WITH_AESNI #define GET_INIT(strength) \@@ -171,6 +180,8 @@ 	((cbc_f) (cryptonite_aes_branch_table[DECRYPT_CBC_128 + strength])) #define GET_CTR_ENCRYPT(strength) \ 	((ctr_f) (cryptonite_aes_branch_table[ENCRYPT_CTR_128 + strength]))+#define GET_C32_ENCRYPT(strength) \+	((ctr_f) (cryptonite_aes_branch_table[ENCRYPT_C32_128 + strength])) #define GET_XTS_ENCRYPT(strength) \ 	((xts_f) (cryptonite_aes_branch_table[ENCRYPT_XTS_128 + strength])) #define GET_XTS_DECRYPT(strength) \@@ -191,8 +202,10 @@ 	(((block_f) (cryptonite_aes_branch_table[ENCRYPT_BLOCK_128 + k->strength]))(o,k,i)) #define cryptonite_aes_decrypt_block(o,k,i) \ 	(((block_f) (cryptonite_aes_branch_table[DECRYPT_BLOCK_128 + k->strength]))(o,k,i))-#define cryptonite_gf_mul(a,b) \-	(((gf_mul_f) (cryptonite_aes_branch_table[GHASH_GF_MUL]))(a,b))+#define cryptonite_hinit(t,h) \+	(((hinit_f) (cryptonite_aes_branch_table[GHASH_HINIT]))(t,h))+#define cryptonite_gf_mul(a,t) \+	(((gf_mul_f) (cryptonite_aes_branch_table[GHASH_GF_MUL]))(a,t)) #else #define GET_INIT(strenght) cryptonite_aes_generic_init #define GET_ECB_ENCRYPT(strength) cryptonite_aes_generic_encrypt_ecb@@ -200,6 +213,7 @@ #define GET_CBC_ENCRYPT(strength) cryptonite_aes_generic_encrypt_cbc #define GET_CBC_DECRYPT(strength) cryptonite_aes_generic_decrypt_cbc #define GET_CTR_ENCRYPT(strength) cryptonite_aes_generic_encrypt_ctr+#define GET_C32_ENCRYPT(strength) cryptonite_aes_generic_encrypt_c32 #define GET_XTS_ENCRYPT(strength) cryptonite_aes_generic_encrypt_xts #define GET_XTS_DECRYPT(strength) cryptonite_aes_generic_decrypt_xts #define GET_GCM_ENCRYPT(strength) cryptonite_aes_generic_gcm_encrypt@@ -210,14 +224,23 @@ #define GET_CCM_DECRYPT(strength) cryptonite_aes_generic_ccm_decrypt #define cryptonite_aes_encrypt_block(o,k,i) cryptonite_aes_generic_encrypt_block(o,k,i) #define cryptonite_aes_decrypt_block(o,k,i) cryptonite_aes_generic_decrypt_block(o,k,i)-#define cryptonite_gf_mul(a,b) cryptonite_aes_generic_gf_mul(a,b)+#define cryptonite_hinit(t,h) cryptonite_aes_generic_hinit(t,h)+#define cryptonite_gf_mul(a,t) cryptonite_aes_generic_gf_mul(a,t) #endif +#define CPU_AESNI        0+#define CPU_PCLMUL       1+#define CPU_OPTION_COUNT 2++static uint8_t cryptonite_aes_cpu_options[CPU_OPTION_COUNT] = {};+ #if defined(ARCH_X86) && defined(WITH_AESNI) static void initialize_table_ni(int aesni, int pclmul) { 	if (!aesni) 		return;+	cryptonite_aes_cpu_options[CPU_AESNI] = 1;+ 	cryptonite_aes_branch_table[INIT_128] = cryptonite_aesni_init; 	cryptonite_aes_branch_table[INIT_256] = cryptonite_aesni_init; @@ -238,6 +261,9 @@ 	/* CTR */ 	cryptonite_aes_branch_table[ENCRYPT_CTR_128] = cryptonite_aesni_encrypt_ctr128; 	cryptonite_aes_branch_table[ENCRYPT_CTR_256] = cryptonite_aesni_encrypt_ctr256;+	/* CTR with 32-bit wrapping */+	cryptonite_aes_branch_table[ENCRYPT_C32_128] = cryptonite_aesni_encrypt_c32_128;+	cryptonite_aes_branch_table[ENCRYPT_C32_256] = cryptonite_aesni_encrypt_c32_256; 	/* XTS */ 	cryptonite_aes_branch_table[ENCRYPT_XTS_128] = cryptonite_aesni_encrypt_xts128; 	cryptonite_aes_branch_table[ENCRYPT_XTS_256] = cryptonite_aesni_encrypt_xts256;@@ -252,13 +278,24 @@ #ifdef WITH_PCLMUL 	if (!pclmul) 		return;+	cryptonite_aes_cpu_options[CPU_PCLMUL] = 1;+ 	/* GHASH */-	cryptonite_aes_branch_table[GHASH_GF_MUL]    = cryptonite_aesni_gf_mul;+	cryptonite_aes_branch_table[GHASH_HINIT]     = cryptonite_aesni_hinit_pclmul,+	cryptonite_aes_branch_table[GHASH_GF_MUL]    = cryptonite_aesni_gf_mul_pclmul, 	cryptonite_aesni_init_pclmul(); #endif } #endif +uint8_t *cryptonite_aes_cpu_init(void)+{+#if defined(ARCH_X86) && defined(WITH_AESNI)+	cryptonite_aesni_initialize_hw(initialize_table_ni);+#endif+	return cryptonite_aes_cpu_options;+}+ void cryptonite_aes_initkey(aes_key *key, uint8_t *origkey, uint8_t size) { 	switch (size) {@@ -266,9 +303,7 @@ 	case 24: key->nbr = 12; key->strength = 1; break; 	case 32: key->nbr = 14; key->strength = 2; break; 	}-#if defined(ARCH_X86) && defined(WITH_AESNI)-	cryptonite_aesni_initialize_hw(initialize_table_ni);-#endif+	cryptonite_aes_cpu_init(); 	init_f _init = GET_INIT(key->strength); 	_init(key, origkey, size); }@@ -330,6 +365,12 @@ 	e(output, key, iv, input, len); } +void cryptonite_aes_encrypt_c32(uint8_t *output, aes_key *key, aes_block *iv, uint8_t *input, uint32_t len)+{+	ctr_f e = GET_C32_ENCRYPT(key->strength);+	e(output, key, iv, input, len);+}+ void cryptonite_aes_encrypt_xts(aes_block *output, aes_key *k1, aes_key *k2, aes_block *dataunit,                      uint32_t spoint, aes_block *input, uint32_t nb_blocks) {@@ -382,20 +423,22 @@ static void gcm_ghash_add(aes_gcm *gcm, block128 *b) { 	block128_xor(&gcm->tag, b);-	cryptonite_gf_mul(&gcm->tag, &gcm->h);+	cryptonite_gf_mul(&gcm->tag, gcm->htable); }  void cryptonite_aes_gcm_init(aes_gcm *gcm, aes_key *key, uint8_t *iv, uint32_t len) {+	block128 h; 	gcm->length_aad = 0; 	gcm->length_input = 0; -	block128_zero(&gcm->h);+	block128_zero(&h); 	block128_zero(&gcm->tag); 	block128_zero(&gcm->iv);  	/* prepare H : encrypt_K(0^128) */-	cryptonite_aes_encrypt_block(&gcm->h, key, &gcm->h);+	cryptonite_aes_encrypt_block(&h, key, &h);+	cryptonite_hinit(gcm->htable, &h);  	if (len == 12) { 		block128_copy_bytes(&gcm->iv, iv, 12);@@ -405,15 +448,15 @@ 		int i; 		for (; len >= 16; len -= 16, iv += 16) { 			block128_xor(&gcm->iv, (block128 *) iv);-			cryptonite_gf_mul(&gcm->iv, &gcm->h);+			cryptonite_gf_mul(&gcm->iv, gcm->htable); 		} 		if (len > 0) { 			block128_xor_bytes(&gcm->iv, iv, len);-			cryptonite_gf_mul(&gcm->iv, &gcm->h);+			cryptonite_gf_mul(&gcm->iv, gcm->htable); 		} 		for (i = 15; origlen; --i, origlen >>= 8) 			gcm->iv.b[i] ^= (uint8_t) origlen;-		cryptonite_gf_mul(&gcm->iv, &gcm->h);+		cryptonite_gf_mul(&gcm->iv, gcm->htable); 	}  	block128_copy_aligned(&gcm->civ, &gcm->iv);@@ -507,7 +550,7 @@ static void ccm_cbcmac_add(aes_ccm* ccm, aes_key* key, block128* bi) { 	block128_xor_aligned(&ccm->xi, bi);-	cryptonite_aes_generic_encrypt_block(&ccm->xi, key, &ccm->xi);+	cryptonite_aes_encrypt_block(&ccm->xi, key, &ccm->xi); }  /* even though it is possible to support message size as large as 2^64, we support up to 2^32 only */@@ -765,6 +808,30 @@ 	} } +void cryptonite_aes_generic_encrypt_c32(uint8_t *output, aes_key *key, aes_block *iv, uint8_t *input, uint32_t len)+{+	aes_block block, o;+	uint32_t nb_blocks = len / 16;+	int i;++	/* preload IV in block */+	block128_copy(&block, iv);++	for ( ; nb_blocks-- > 0; block128_inc32_le(&block), output += 16, input += 16) {+		cryptonite_aes_encrypt_block(&o, key, &block);+		block128_vxor((block128 *) output, &o, (block128 *) input);+	}++	if ((len % 16) != 0) {+		cryptonite_aes_encrypt_block(&o, key, &block);+		for (i = 0; i < (len % 16); i++) {+			*output = ((uint8_t *) &o)[i] ^ *input;+			output++;+			input++;+		}+	}+}+ void cryptonite_aes_generic_encrypt_xts(aes_block *output, aes_key *k1, aes_key *k2, aes_block *dataunit,                              uint32_t spoint, aes_block *input, uint32_t nb_blocks) {@@ -811,7 +878,7 @@  	gcm->length_input += length; 	for (; length >= 16; input += 16, output += 16, length -= 16) {-		block128_inc_be(&gcm->civ);+		block128_inc32_be(&gcm->civ);  		cryptonite_aes_encrypt_block(&out, key, &gcm->civ); 		block128_xor(&out, (block128 *) input);@@ -822,7 +889,7 @@ 		aes_block tmp; 		int i; -		block128_inc_be(&gcm->civ);+		block128_inc32_be(&gcm->civ); 		/* create e(civ) in out */ 		cryptonite_aes_encrypt_block(&out, key, &gcm->civ); 		/* initialize a tmp as input and xor it to e(civ) */@@ -844,7 +911,7 @@  	gcm->length_input += length; 	for (; length >= 16; input += 16, output += 16, length -= 16) {-		block128_inc_be(&gcm->civ);+		block128_inc32_be(&gcm->civ);  		cryptonite_aes_encrypt_block(&out, key, &gcm->civ); 		gcm_ghash_add(gcm, (block128 *) input);@@ -855,7 +922,7 @@ 		aes_block tmp; 		int i; -		block128_inc_be(&gcm->civ);+		block128_inc32_be(&gcm->civ);  		block128_zero(&tmp); 		block128_copy_bytes(&tmp, input, length);@@ -987,4 +1054,56 @@ void cryptonite_aes_generic_ocb_decrypt(uint8_t *output, aes_ocb *ocb, aes_key *key, uint8_t *input, uint32_t length) { 	ocb_generic_crypt(output, ocb, key, input, length, 0);+}++static inline void gf_mulx_rev(block128 *a, const block128 *h)+{+	uint64_t v1 = cpu_to_le64(h->q[0]);+	uint64_t v0 = cpu_to_le64(h->q[1]);+	a->q[1] = cpu_to_be64(v1 >> 1 | v0 << 63);+	a->q[0] = cpu_to_be64(v0 >> 1 ^ ((0-(v1 & 1)) & 0xe100000000000000ULL));+}++void cryptonite_aes_polyval_init(aes_polyval *ctx, const aes_block *h)+{+	aes_block r;++	/* ByteReverse(S_0) = 0 */+	block128_zero(&ctx->s);++	/* ByteReverse(H) * x */+	gf_mulx_rev(&r, h);+	cryptonite_hinit(ctx->htable, &r);+}++void cryptonite_aes_polyval_update(aes_polyval *ctx, const uint8_t *input, uint32_t length)+{+	aes_block r;+	const uint8_t *p;+	uint32_t sz;++	/* This automatically pads with zeros if input is not a multiple of the+	   block size. */+	for (p = input; length > 0; p += 16, length -= sz)+	{+		sz = length < 16 ? length : 16;++		/* ByteReverse(X_j) */+		block128_zero(&r);+		memcpy(&r, p, sz);+		block128_byte_reverse(&r);++		/* ByteReverse(S_{j-1}) + ByteReverse(X_j) */+		block128_xor_aligned(&ctx->s, &r);++		/* ByteReverse(S_j) */+		cryptonite_gf_mul(&ctx->s, ctx->htable);+	}+}++void cryptonite_aes_polyval_finalize(aes_polyval *ctx, aes_block *dst)+{+	/* S_s */+	block128_copy_aligned(dst, &ctx->s);+	block128_byte_reverse(dst); }
cbits/cryptonite_aes.h view
@@ -45,10 +45,10 @@ 	uint8_t data[16*14*2]; } aes_key; -/* size = 4*16+2*8= 80 */+/* size = 19*16+2*8= 320 */ typedef struct { 	aes_block tag;-	aes_block h;+	aes_block htable[16]; 	aes_block iv; 	aes_block civ; 	uint64_t length_aad;@@ -77,6 +77,12 @@ 	block128 li[4]; } aes_ocb; +/* size = 17*16= 272 */+typedef struct {+	aes_block htable[16];+	aes_block s;+} aes_polyval;+ /* in bytes: either 16,24,32 */ void cryptonite_aes_initkey(aes_key *ctx, uint8_t *key, uint8_t size); @@ -114,5 +120,11 @@ void cryptonite_aes_ccm_encrypt(uint8_t *output, aes_ccm *ccm, aes_key *key, uint8_t *input, uint32_t length); void cryptonite_aes_ccm_decrypt(uint8_t *output, aes_ccm *ccm, aes_key *key, uint8_t *input, uint32_t length); void cryptonite_aes_ccm_finish(uint8_t *tag, aes_ccm *ccm, aes_key *key);++uint8_t *cryptonite_aes_cpu_init(void);++void cryptonite_aes_polyval_init(aes_polyval *ctx, const aes_block *h);+void cryptonite_aes_polyval_update(aes_polyval *ctx, const uint8_t *input, uint32_t length);+void cryptonite_aes_polyval_finalize(aes_polyval *ctx, aes_block *dst);  #endif
cbits/cryptonite_chacha.c view
@@ -98,7 +98,6 @@                                  uint32_t ivlen, const uint8_t *iv) { 	const uint8_t *constants = (keylen == 32) ? sigma : tau;-	int i;  	ASSERT_ALIGNMENT(constants, 4); 
cbits/cryptonite_rdrand.c view
@@ -91,7 +91,7 @@ } #endif -/* Returns the number of bytes succesfully generated */+/* Returns the number of bytes successfully generated */ int cryptonite_get_rand_bytes(uint8_t *buffer, size_t len) { 	RDRAND_T tmp;
cbits/cryptonite_salsa.c view
@@ -120,7 +120,6 @@                                 uint32_t ivlen, const uint8_t *iv) { 	const uint8_t *constants = (keylen == 32) ? sigma : tau;-	int i;  	st->d[0] = load_le32_aligned(constants + 0); 	st->d[5] = load_le32_aligned(constants + 4);
cbits/cryptonite_skein256.c view
@@ -167,7 +167,6 @@ void cryptonite_skein256_finalize(struct skein256_ctx *ctx, uint32_t hashlen, uint8_t *out) { 	uint32_t outsize;-	uint64_t *p = (uint64_t *) out; 	uint64_t x[4]; 	int i, j, n; 
cbits/cryptonite_skein512.c view
@@ -185,7 +185,6 @@ void cryptonite_skein512_finalize(struct skein512_ctx *ctx, uint32_t hashlen, uint8_t *out) { 	uint32_t outsize;-	uint64_t *p = (uint64_t *) out; 	uint64_t x[8]; 	int i, j, n; 
cbits/cryptonite_whirlpool.c view
@@ -777,7 +777,6 @@ 	uint64_t K[8];        /* the round key */ 	uint64_t block[8];    /* mu(buffer) */ 	uint64_t state[8];    /* the cipher state */-	uint64_t L[8]; 	uint8_t *buffer = ctx->buffer;  	/*
cbits/cryptonite_xsalsa.c view
@@ -47,13 +47,27 @@        (x6, x7, x8, x9) is the first 128 bits of a 192-bit nonce   */   cryptonite_salsa_init_core(&ctx->st, keylen, key, 8, iv);-  ctx->st.d[ 8] = load_le32(iv + 8);-  ctx->st.d[ 9] = load_le32(iv + 12); +  /* Continue initialization in a separate function that may also+     be called independently */+  cryptonite_xsalsa_derive(ctx, ivlen - 8, iv + 8);+}++void cryptonite_xsalsa_derive(cryptonite_salsa_context *ctx,+                              uint32_t ivlen, const uint8_t *iv)+{+  /* Finish creating initial 512-bit input block:+       (x6, x7, x8, x9) is the first 128 bits of a 192-bit nonce++     Except iv has been shifted by 64 bits so there are now only 128 bits ahead.+  */+  ctx->st.d[ 8] += load_le32(iv + 0);+  ctx->st.d[ 9] += load_le32(iv + 4);+   /* Compute (z0, z1, . . . , z15) = doubleround ^(r/2) (x0, x1, . . . , x15) */   block hSalsa;   memset(&hSalsa, 0, sizeof(block));-  cryptonite_salsa_core_xor(nb_rounds, &hSalsa, &ctx->st);+  cryptonite_salsa_core_xor(ctx->nb_rounds, &hSalsa, &ctx->st);     /* Build a new 512-bit input block (x′0, x′1, . . . , x′15):        (x′0, x′5, x′10, x′15) is the Salsa20 constant@@ -69,8 +83,8 @@   ctx->st.d[12] = hSalsa.d[ 7] - ctx->st.d[ 7];   ctx->st.d[13] = hSalsa.d[ 8] - ctx->st.d[ 8];   ctx->st.d[14] = hSalsa.d[ 9] - ctx->st.d[ 9];-  ctx->st.d[ 6] = load_le32(iv + 16);-  ctx->st.d[ 7] = load_le32(iv + 20);+  ctx->st.d[ 6] = load_le32(iv + 8);+  ctx->st.d[ 7] = load_le32(iv + 12);   ctx->st.d[ 8] = 0;   ctx->st.d[ 9] = 0; }
cbits/cryptonite_xsalsa.h view
@@ -33,5 +33,6 @@ #include "cryptonite_salsa.h"  void cryptonite_xsalsa_init(cryptonite_salsa_context *ctx, uint8_t nb_rounds, uint32_t keylen, const uint8_t *key, uint32_t ivlen, const uint8_t *iv);+void cryptonite_xsalsa_derive(cryptonite_salsa_context *ctx, uint32_t ivlen, const uint8_t *iv);  #endif
+ cbits/include32/p256/p256.h view
@@ -0,0 +1,167 @@+/*+ * Copyright 2013 The Android Open Source Project+ *+ * Redistribution and use in source and binary forms, with or without+ * modification, are permitted provided that the following conditions are met:+ *     * Redistributions of source code must retain the above copyright+ *       notice, this list of conditions and the following disclaimer.+ *     * Redistributions in binary form must reproduce the above copyright+ *       notice, this list of conditions and the following disclaimer in the+ *       documentation and/or other materials provided with the distribution.+ *     * Neither the name of Google Inc. nor the names of its contributors may+ *       be used to endorse or promote products derived from this software+ *       without specific prior written permission.+ *+ * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+ * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+ */++#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_+#define SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_++// Collection of routines manipulating 256 bit unsigned integers.+// Just enough to implement ecdsa-p256 and related algorithms.++#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++#define P256_BITSPERDIGIT 32+#define P256_NDIGITS 8+#define P256_NBYTES 32++// n' such as n * n' = -1 mod (2^32)+#define P256_MONTGOMERY_FACTOR 0xEE00BC4F++#define P256_LITERAL(lo,hi) (lo), (hi)++typedef int cryptonite_p256_err;+typedef uint32_t cryptonite_p256_digit;+typedef int32_t cryptonite_p256_sdigit;+typedef uint64_t cryptonite_p256_ddigit;+typedef int64_t cryptonite_p256_sddigit;++// Defining cryptonite_p256_int as struct to leverage struct assigment.+typedef struct {+  cryptonite_p256_digit a[P256_NDIGITS];+} cryptonite_p256_int;++extern const cryptonite_p256_int cryptonite_SECP256r1_n;  // Curve order+extern const cryptonite_p256_int cryptonite_SECP256r1_p;  // Curve prime+extern const cryptonite_p256_int cryptonite_SECP256r1_b;  // Curve param++// Initialize a cryptonite_p256_int to zero.+void cryptonite_p256_init(cryptonite_p256_int* a);++// Clear a cryptonite_p256_int to zero.+void cryptonite_p256_clear(cryptonite_p256_int* a);++// Return bit. Index 0 is least significant.+int cryptonite_p256_get_bit(const cryptonite_p256_int* a, int index);++// b := a % MOD+void cryptonite_p256_mod(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    cryptonite_p256_int* b);++// c := a * (top_b | b) % MOD+void cryptonite_p256_modmul(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    const cryptonite_p256_digit top_b,+    const cryptonite_p256_int* b,+    cryptonite_p256_int* c);++// b := 1 / a % MOD+// MOD best be SECP256r1_n+void cryptonite_p256_modinv(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    cryptonite_p256_int* b);++// b := 1 / a % MOD+// MOD best be SECP256r1_n+// Faster than cryptonite_p256_modinv()+void cryptonite_p256_modinv_vartime(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    cryptonite_p256_int* b);++// b := a << (n % P256_BITSPERDIGIT)+// Returns the bits shifted out of most significant digit.+cryptonite_p256_digit cryptonite_p256_shl(const cryptonite_p256_int* a, int n, cryptonite_p256_int* b);++// b := a >> (n % P256_BITSPERDIGIT)+void cryptonite_p256_shr(const cryptonite_p256_int* a, int n, cryptonite_p256_int* b);++int cryptonite_p256_is_zero(const cryptonite_p256_int* a);+int cryptonite_p256_is_odd(const cryptonite_p256_int* a);+int cryptonite_p256_is_even(const cryptonite_p256_int* a);++// Returns -1, 0 or 1.+int cryptonite_p256_cmp(const cryptonite_p256_int* a, const cryptonite_p256_int *b);++// c: = a - b+// Returns -1 on borrow.+int cryptonite_p256_sub(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c);++// c := a + b+// Returns 1 on carry.+int cryptonite_p256_add(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c);++// c := a + (single digit)b+// Returns carry 1 on carry.+int cryptonite_p256_add_d(const cryptonite_p256_int* a, cryptonite_p256_digit b, cryptonite_p256_int* c);++// ec routines.++// {out_x,out_y} := nG+void cryptonite_p256_base_point_mul(const cryptonite_p256_int *n,+                         cryptonite_p256_int *out_x,+                         cryptonite_p256_int *out_y);++// {out_x,out_y} := n{in_x,in_y}+void cryptonite_p256_point_mul(const cryptonite_p256_int *n,+                    const cryptonite_p256_int *in_x,+                    const cryptonite_p256_int *in_y,+                    cryptonite_p256_int *out_x,+                    cryptonite_p256_int *out_y);++// {out_x,out_y} := n1G + n2{in_x,in_y}+void cryptonite_p256_points_mul_vartime(+    const cryptonite_p256_int *n1, const cryptonite_p256_int *n2,+    const cryptonite_p256_int *in_x, const cryptonite_p256_int *in_y,+    cryptonite_p256_int *out_x, cryptonite_p256_int *out_y);++// Return whether point {x,y} is on curve.+int cryptonite_p256_is_valid_point(const cryptonite_p256_int* x, const cryptonite_p256_int* y);++// Outputs big-endian binary form. No leading zero skips.+void cryptonite_p256_to_bin(const cryptonite_p256_int* src, uint8_t dst[P256_NBYTES]);++// Reads from big-endian binary form,+// thus pre-pad with leading zeros if short.+void cryptonite_p256_from_bin(const uint8_t src[P256_NBYTES], cryptonite_p256_int* dst);++#define P256_DIGITS(x) ((x)->a)+#define P256_DIGIT(x,y) ((x)->a[y])++#define P256_ZERO {{0}}+#define P256_ONE {{1}}++#ifdef __cplusplus+}+#endif++#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_
+ cbits/include32/p256/p256_gf.h view
@@ -0,0 +1,779 @@+/*+ * Copyright 2013 The Android Open Source Project+ *+ * Redistribution and use in source and binary forms, with or without+ * modification, are permitted provided that the following conditions are met:+ *     * Redistributions of source code must retain the above copyright+ *       notice, this list of conditions and the following disclaimer.+ *     * Redistributions in binary form must reproduce the above copyright+ *       notice, this list of conditions and the following disclaimer in the+ *       documentation and/or other materials provided with the distribution.+ *     * Neither the name of Google Inc. nor the names of its contributors may+ *       be used to endorse or promote products derived from this software+ *       without specific prior written permission.+ *+ * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+ * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+ */++// This is an implementation of the P256 finite field. It's written to be+// portable and still constant-time.+//+// WARNING: Implementing these functions in a constant-time manner is far from+//          obvious. Be careful when touching this code.+//+// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background.++#include <stdint.h>+#include <stdio.h>++#include <string.h>+#include <stdlib.h>++#include "p256/p256.h"++typedef uint8_t u8;+typedef uint32_t u32;+typedef int32_t s32;+typedef uint64_t u64;++/* Our field elements are represented as nine 32-bit limbs.+ *+ * The value of an felem (field element) is:+ *   x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228)+ *+ * That is, each limb is alternately 29 or 28-bits wide in little-endian+ * order.+ *+ * This means that an felem hits 2**257, rather than 2**256 as we would like. A+ * 28, 29, ... pattern would cause us to hit 2**256, but that causes problems+ * when multiplying as terms end up one bit short of a limb which would require+ * much bit-shifting to correct.+ *+ * Finally, the values stored in an felem are in Montgomery form. So the value+ * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.+ */+typedef u32 limb;+#define NLIMBS 9+typedef limb felem[NLIMBS];++static const limb kBottom28Bits = 0xfffffff;+static const limb kBottom29Bits = 0x1fffffff;++/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and+ * 28-bit words. */+static const felem kOne = {+    2, 0, 0, 0xffff800,+    0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff,+    0+};+static const felem kZero = {0};+static const felem kP = {+    0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff,+    0, 0, 0x200000, 0xf000000,+    0xfffffff+};+static const felem k2P = {+    0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff,+    0, 0, 0x400000, 0xe000000,+    0x1fffffff+};+/* kPrecomputed contains precomputed values to aid the calculation of scalar+ * multiples of the base point, G. It's actually two, equal length, tables+ * concatenated.+ *+ * The first table contains (x,y) felem pairs for 16 multiples of the base+ * point, G.+ *+ *   Index  |  Index (binary) | Value+ *       0  |           0000  | 0G (all zeros, omitted)+ *       1  |           0001  | G+ *       2  |           0010  | 2**64G+ *       3  |           0011  | 2**64G + G+ *       4  |           0100  | 2**128G+ *       5  |           0101  | 2**128G + G+ *       6  |           0110  | 2**128G + 2**64G+ *       7  |           0111  | 2**128G + 2**64G + G+ *       8  |           1000  | 2**192G+ *       9  |           1001  | 2**192G + G+ *      10  |           1010  | 2**192G + 2**64G+ *      11  |           1011  | 2**192G + 2**64G + G+ *      12  |           1100  | 2**192G + 2**128G+ *      13  |           1101  | 2**192G + 2**128G + G+ *      14  |           1110  | 2**192G + 2**128G + 2**64G+ *      15  |           1111  | 2**192G + 2**128G + 2**64G + G+ *+ * The second table follows the same style, but the terms are 2**32G,+ * 2**96G, 2**160G, 2**224G.+ *+ * This is ~2KB of data. */+static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {+    0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee,+    0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3,+    0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c,+    0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22,+    0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050,+    0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b,+    0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa,+    0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2,+    0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609,+    0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581,+    0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca,+    0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33,+    0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6,+    0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd,+    0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0,+    0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881,+    0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a,+    0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26,+    0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b,+    0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023,+    0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133,+    0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa,+    0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29,+    0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc,+    0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8,+    0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59,+    0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39,+    0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689,+    0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa,+    0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3,+    0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1,+    0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f,+    0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72,+    0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d,+    0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b,+    0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a,+    0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a,+    0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f,+    0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb,+    0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc,+    0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9,+    0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce,+    0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2,+    0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca,+    0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229,+    0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57,+    0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c,+    0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa,+    0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651,+    0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec,+    0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7,+    0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c,+    0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927,+    0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298,+    0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8,+    0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2,+    0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d,+    0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4,+    0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8,+    0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78,+};+++/* Field element operations: */++/* NON_ZERO_TO_ALL_ONES returns:+ *   0xffffffff for 0 < x <= 2**31+ *   0 for x == 0 or x > 2**31.+ *+ * x must be a u32 or an equivalent type such as limb. */+#define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1)++/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,+ * which is a term at 2**257.+ *+ * On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28.+ * On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. */+static void felem_reduce_carry(felem inout, limb carry) {+  const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry);++  inout[0] += carry << 1;+  inout[3] += 0x10000000 & carry_mask;+  /* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the+   * previous line therefore this doesn't underflow. */+  inout[3] -= carry << 11;+  inout[4] += (0x20000000 - 1) & carry_mask;+  inout[5] += (0x10000000 - 1) & carry_mask;+  inout[6] += (0x20000000 - 1) & carry_mask;+  inout[6] -= carry << 22;+  /* This may underflow if carry is non-zero but, if so, we'll fix it in the+   * next line. */+  inout[7] -= 1 & carry_mask;+  inout[7] += carry << 25;+}++/* felem_sum sets out = in+in2.+ *+ * On entry, in[i]+in2[i] must not overflow a 32-bit word.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */+static void felem_sum(felem out, const felem in, const felem in2) {+  limb carry = 0;+  unsigned i;++  for (i = 0;; i++) {+    out[i] = in[i] + in2[i];+    out[i] += carry;+    carry = out[i] >> 29;+    out[i] &= kBottom29Bits;++    i++;+    if (i == NLIMBS)+      break;++    out[i] = in[i] + in2[i];+    out[i] += carry;+    carry = out[i] >> 28;+    out[i] &= kBottom28Bits;+  }++  felem_reduce_carry(out, carry);+}++#define two31m3 (((limb)1) << 31) - (((limb)1) << 3)+#define two30m2 (((limb)1) << 30) - (((limb)1) << 2)+#define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2)+#define two31m2 (((limb)1) << 31) - (((limb)1) << 2)+#define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2)+#define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2)++/* zero31 is 0 mod p. */+static const felem zero31 = { two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2 };++/* felem_diff sets out = in-in2.+ *+ * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and+ *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */+static void felem_diff(felem out, const felem in, const felem in2) {+  limb carry = 0;+  unsigned i;++   for (i = 0;; i++) {+    out[i] = in[i] - in2[i];+    out[i] += zero31[i];+    out[i] += carry;+    carry = out[i] >> 29;+    out[i] &= kBottom29Bits;++    i++;+    if (i == NLIMBS)+      break;++    out[i] = in[i] - in2[i];+    out[i] += zero31[i];+    out[i] += carry;+    carry = out[i] >> 28;+    out[i] &= kBottom28Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words+ * with the same 29,28,... bit positions as an felem.+ *+ * The values in felems are in Montgomery form: x*R mod p where R = 2**257.+ * Since we just multiplied two Montgomery values together, the result is+ * x*y*R*R mod p. We wish to divide by R in order for the result also to be+ * in Montgomery form.+ *+ * On entry: tmp[i] < 2**64+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */+static void felem_reduce_degree(felem out, u64 tmp[17]) {+   /* The following table may be helpful when reading this code:+    *+    * Limb number:   0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...+    * Width (bits):  29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29+    * Start bit:     0 | 29| 57| 86|114|143|171|200|228|257|285+    *   (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 */+  limb tmp2[18], carry, x, xMask;+  unsigned i;++  /* tmp contains 64-bit words with the same 29,28,29-bit positions as an+   * felem. So the top of an element of tmp might overlap with another+   * element two positions down. The following loop eliminates this+   * overlap. */+  tmp2[0] = (limb)(tmp[0] & kBottom29Bits);++  /* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try+   * and hint to the compiler that it can do a single-word shift by selecting+   * the right register rather than doing a double-word shift and truncating+   * afterwards. */+  tmp2[1] = ((limb) tmp[0]) >> 29;+  tmp2[1] |= (((limb)(tmp[0] >> 32)) << 3) & kBottom28Bits;+  tmp2[1] += ((limb) tmp[1]) & kBottom28Bits;+  carry = tmp2[1] >> 28;+  tmp2[1] &= kBottom28Bits;++  for (i = 2; i < 17; i++) {+    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;+    tmp2[i] += ((limb)(tmp[i - 1])) >> 28;+    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 4) & kBottom29Bits;+    tmp2[i] += ((limb) tmp[i]) & kBottom29Bits;+    tmp2[i] += carry;+    carry = tmp2[i] >> 29;+    tmp2[i] &= kBottom29Bits;++    i++;+    if (i == 17)+      break;+    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;+    tmp2[i] += ((limb)(tmp[i - 1])) >> 29;+    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 3) & kBottom28Bits;+    tmp2[i] += ((limb) tmp[i]) & kBottom28Bits;+    tmp2[i] += carry;+    carry = tmp2[i] >> 28;+    tmp2[i] &= kBottom28Bits;+  }++  tmp2[17] = ((limb)(tmp[15] >> 32)) >> 25;+  tmp2[17] += ((limb)(tmp[16])) >> 29;+  tmp2[17] += (((limb)(tmp[16] >> 32)) << 3);+  tmp2[17] += carry;++  /* Montgomery elimination of terms.+   *+   * Since R is 2**257, we can divide by R with a bitwise shift if we can+   * ensure that the right-most 257 bits are all zero. We can make that true by+   * adding multiplies of p without affecting the value.+   *+   * So we eliminate limbs from right to left. Since the bottom 29 bits of p+   * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.+   * We can do that for 8 further limbs and then right shift to eliminate the+   * extra factor of R. */+  for (i = 0;; i += 2) {+    tmp2[i + 1] += tmp2[i] >> 29;+    x = tmp2[i] & kBottom29Bits;+    xMask = NON_ZERO_TO_ALL_ONES(x);+    tmp2[i] = 0;++    /* The bounds calculations for this loop are tricky. Each iteration of+     * the loop eliminates two words by adding values to words to their+     * right.+     *+     * The following table contains the amounts added to each word (as an+     * offset from the value of i at the top of the loop). The amounts are+     * accounted for from the first and second half of the loop separately+     * and are written as, for example, 28 to mean a value <2**28.+     *+     * Word:                   3   4   5   6   7   8   9   10+     * Added in top half:     28  11      29  21  29  28+     *                                        28  29+     *                                            29+     * Added in bottom half:      29  10      28  21  28   28+     *                                            29+     *+     * The value that is currently offset 7 will be offset 5 for the next+     * iteration and then offset 3 for the iteration after that. Therefore+     * the total value added will be the values added at 7, 5 and 3.+     *+     * The following table accumulates these values. The sums at the bottom+     * are written as, for example, 29+28, to mean a value < 2**29+2**28.+     *+     * Word:                   3   4   5   6   7   8   9  10  11  12  13+     *                        28  11  10  29  21  29  28  28  28  28  28+     *                            29  28  11  28  29  28  29  28  29  28+     *                                    29  28  21  21  29  21  29  21+     *                                        10  29  28  21  28  21  28+     *                                        28  29  28  29  28  29  28+     *                                            11  10  29  10  29  10+     *                                            29  28  11  28  11+     *                                                    29      29+     *                        --------------------------------------------+     *                                                30+ 31+ 30+ 31+ 30++     *                                                28+ 29+ 28+ 29+ 21++     *                                                21+ 28+ 21+ 28+ 10+     *                                                10  21+ 10  21++     *                                                    11      11+     *+     * So the greatest amount is added to tmp2[10] and tmp2[12]. If+     * tmp2[10/12] has an initial value of <2**29, then the maximum value+     * will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32,+     * as required. */+    tmp2[i + 3] += (x << 10) & kBottom28Bits;+    tmp2[i + 4] += (x >> 18);++    tmp2[i + 6] += (x << 21) & kBottom29Bits;+    tmp2[i + 7] += x >> 8;++    /* At position 200, which is the starting bit position for word 7, we+     * have a factor of 0xf000000 = 2**28 - 2**24. */+    tmp2[i + 7] += 0x10000000 & xMask;+    /* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */+    tmp2[i + 8] += (x - 1) & xMask;+    tmp2[i + 7] -= (x << 24) & kBottom28Bits;+    tmp2[i + 8] -= x >> 4;++    tmp2[i + 8] += 0x20000000 & xMask;+    tmp2[i + 8] -= x;+    tmp2[i + 8] += (x << 28) & kBottom29Bits;+    tmp2[i + 9] += ((x >> 1) - 1) & xMask;++    if (i+1 == NLIMBS)+      break;+    tmp2[i + 2] += tmp2[i + 1] >> 28;+    x = tmp2[i + 1] & kBottom28Bits;+    xMask = NON_ZERO_TO_ALL_ONES(x);+    tmp2[i + 1] = 0;++    tmp2[i + 4] += (x << 11) & kBottom29Bits;+    tmp2[i + 5] += (x >> 18);++    tmp2[i + 7] += (x << 21) & kBottom28Bits;+    tmp2[i + 8] += x >> 7;++    /* At position 199, which is the starting bit of the 8th word when+     * dealing with a context starting on an odd word, we have a factor of+     * 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th+     * word from i+1 is i+8. */+    tmp2[i + 8] += 0x20000000 & xMask;+    tmp2[i + 9] += (x - 1) & xMask;+    tmp2[i + 8] -= (x << 25) & kBottom29Bits;+    tmp2[i + 9] -= x >> 4;++    tmp2[i + 9] += 0x10000000 & xMask;+    tmp2[i + 9] -= x;+    tmp2[i + 10] += (x - 1) & xMask;+  }++  /* We merge the right shift with a carry chain. The words above 2**257 have+   * widths of 28,29,... which we need to correct when copying them down.  */+  carry = 0;+  for (i = 0; i < 8; i++) {+    /* The maximum value of tmp2[i + 9] occurs on the first iteration and+     * is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is+     * therefore safe. */+    out[i] = tmp2[i + 9];+    out[i] += carry;+    out[i] += (tmp2[i + 10] << 28) & kBottom29Bits;+    carry = out[i] >> 29;+    out[i] &= kBottom29Bits;++    i++;+    out[i] = tmp2[i + 9] >> 1;+    out[i] += carry;+    carry = out[i] >> 28;+    out[i] &= kBottom28Bits;+  }++  out[8] = tmp2[17];+  out[8] += carry;+  carry = out[8] >> 29;+  out[8] &= kBottom29Bits;++  felem_reduce_carry(out, carry);+}++/* felem_square sets out=in*in.+ *+ * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */+static void felem_square(felem out, const felem in) {+  u64 tmp[17];++  tmp[0] = ((u64) in[0]) * in[0];+  tmp[1] = ((u64) in[0]) * (in[1] << 1);+  tmp[2] = ((u64) in[0]) * (in[2] << 1) ++           ((u64) in[1]) * (in[1] << 1);+  tmp[3] = ((u64) in[0]) * (in[3] << 1) ++           ((u64) in[1]) * (in[2] << 1);+  tmp[4] = ((u64) in[0]) * (in[4] << 1) ++           ((u64) in[1]) * (in[3] << 2) + ((u64) in[2]) * in[2];+  tmp[5] = ((u64) in[0]) * (in[5] << 1) + ((u64) in[1]) *+           (in[4] << 1) + ((u64) in[2]) * (in[3] << 1);+  tmp[6] = ((u64) in[0]) * (in[6] << 1) + ((u64) in[1]) *+           (in[5] << 2) + ((u64) in[2]) * (in[4] << 1) ++           ((u64) in[3]) * (in[3] << 1);+  tmp[7] = ((u64) in[0]) * (in[7] << 1) + ((u64) in[1]) *+           (in[6] << 1) + ((u64) in[2]) * (in[5] << 1) ++           ((u64) in[3]) * (in[4] << 1);+  /* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60,+   * which is < 2**64 as required. */+  tmp[8] = ((u64) in[0]) * (in[8] << 1) + ((u64) in[1]) *+           (in[7] << 2) + ((u64) in[2]) * (in[6] << 1) ++           ((u64) in[3]) * (in[5] << 2) + ((u64) in[4]) * in[4];+  tmp[9] = ((u64) in[1]) * (in[8] << 1) + ((u64) in[2]) *+           (in[7] << 1) + ((u64) in[3]) * (in[6] << 1) ++           ((u64) in[4]) * (in[5] << 1);+  tmp[10] = ((u64) in[2]) * (in[8] << 1) + ((u64) in[3]) *+            (in[7] << 2) + ((u64) in[4]) * (in[6] << 1) ++            ((u64) in[5]) * (in[5] << 1);+  tmp[11] = ((u64) in[3]) * (in[8] << 1) + ((u64) in[4]) *+            (in[7] << 1) + ((u64) in[5]) * (in[6] << 1);+  tmp[12] = ((u64) in[4]) * (in[8] << 1) ++            ((u64) in[5]) * (in[7] << 2) + ((u64) in[6]) * in[6];+  tmp[13] = ((u64) in[5]) * (in[8] << 1) ++            ((u64) in[6]) * (in[7] << 1);+  tmp[14] = ((u64) in[6]) * (in[8] << 1) ++            ((u64) in[7]) * (in[7] << 1);+  tmp[15] = ((u64) in[7]) * (in[8] << 1);+  tmp[16] = ((u64) in[8]) * in[8];++  felem_reduce_degree(out, tmp);+}++/* felem_mul sets out=in*in2.+ *+ * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and+ *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */+static void felem_mul(felem out, const felem in, const felem in2) {+  u64 tmp[17];++  tmp[0] = ((u64) in[0]) * in2[0];+  tmp[1] = ((u64) in[0]) * (in2[1] << 0) ++           ((u64) in[1]) * (in2[0] << 0);+  tmp[2] = ((u64) in[0]) * (in2[2] << 0) + ((u64) in[1]) *+           (in2[1] << 1) + ((u64) in[2]) * (in2[0] << 0);+  tmp[3] = ((u64) in[0]) * (in2[3] << 0) + ((u64) in[1]) *+           (in2[2] << 0) + ((u64) in[2]) * (in2[1] << 0) ++           ((u64) in[3]) * (in2[0] << 0);+  tmp[4] = ((u64) in[0]) * (in2[4] << 0) + ((u64) in[1]) *+           (in2[3] << 1) + ((u64) in[2]) * (in2[2] << 0) ++           ((u64) in[3]) * (in2[1] << 1) ++           ((u64) in[4]) * (in2[0] << 0);+  tmp[5] = ((u64) in[0]) * (in2[5] << 0) + ((u64) in[1]) *+           (in2[4] << 0) + ((u64) in[2]) * (in2[3] << 0) ++           ((u64) in[3]) * (in2[2] << 0) + ((u64) in[4]) *+           (in2[1] << 0) + ((u64) in[5]) * (in2[0] << 0);+  tmp[6] = ((u64) in[0]) * (in2[6] << 0) + ((u64) in[1]) *+           (in2[5] << 1) + ((u64) in[2]) * (in2[4] << 0) ++           ((u64) in[3]) * (in2[3] << 1) + ((u64) in[4]) *+           (in2[2] << 0) + ((u64) in[5]) * (in2[1] << 1) ++           ((u64) in[6]) * (in2[0] << 0);+  tmp[7] = ((u64) in[0]) * (in2[7] << 0) + ((u64) in[1]) *+           (in2[6] << 0) + ((u64) in[2]) * (in2[5] << 0) ++           ((u64) in[3]) * (in2[4] << 0) + ((u64) in[4]) *+           (in2[3] << 0) + ((u64) in[5]) * (in2[2] << 0) ++           ((u64) in[6]) * (in2[1] << 0) ++           ((u64) in[7]) * (in2[0] << 0);+  /* tmp[8] has the greatest value but doesn't overflow. See logic in+   * felem_square. */+  tmp[8] = ((u64) in[0]) * (in2[8] << 0) + ((u64) in[1]) *+           (in2[7] << 1) + ((u64) in[2]) * (in2[6] << 0) ++           ((u64) in[3]) * (in2[5] << 1) + ((u64) in[4]) *+           (in2[4] << 0) + ((u64) in[5]) * (in2[3] << 1) ++           ((u64) in[6]) * (in2[2] << 0) + ((u64) in[7]) *+           (in2[1] << 1) + ((u64) in[8]) * (in2[0] << 0);+  tmp[9] = ((u64) in[1]) * (in2[8] << 0) + ((u64) in[2]) *+           (in2[7] << 0) + ((u64) in[3]) * (in2[6] << 0) ++           ((u64) in[4]) * (in2[5] << 0) + ((u64) in[5]) *+           (in2[4] << 0) + ((u64) in[6]) * (in2[3] << 0) ++           ((u64) in[7]) * (in2[2] << 0) ++           ((u64) in[8]) * (in2[1] << 0);+  tmp[10] = ((u64) in[2]) * (in2[8] << 0) + ((u64) in[3]) *+            (in2[7] << 1) + ((u64) in[4]) * (in2[6] << 0) ++            ((u64) in[5]) * (in2[5] << 1) + ((u64) in[6]) *+            (in2[4] << 0) + ((u64) in[7]) * (in2[3] << 1) ++            ((u64) in[8]) * (in2[2] << 0);+  tmp[11] = ((u64) in[3]) * (in2[8] << 0) + ((u64) in[4]) *+            (in2[7] << 0) + ((u64) in[5]) * (in2[6] << 0) ++            ((u64) in[6]) * (in2[5] << 0) + ((u64) in[7]) *+            (in2[4] << 0) + ((u64) in[8]) * (in2[3] << 0);+  tmp[12] = ((u64) in[4]) * (in2[8] << 0) + ((u64) in[5]) *+            (in2[7] << 1) + ((u64) in[6]) * (in2[6] << 0) ++            ((u64) in[7]) * (in2[5] << 1) ++            ((u64) in[8]) * (in2[4] << 0);+  tmp[13] = ((u64) in[5]) * (in2[8] << 0) + ((u64) in[6]) *+            (in2[7] << 0) + ((u64) in[7]) * (in2[6] << 0) ++            ((u64) in[8]) * (in2[5] << 0);+  tmp[14] = ((u64) in[6]) * (in2[8] << 0) + ((u64) in[7]) *+            (in2[7] << 1) + ((u64) in[8]) * (in2[6] << 0);+  tmp[15] = ((u64) in[7]) * (in2[8] << 0) ++            ((u64) in[8]) * (in2[7] << 0);+  tmp[16] = ((u64) in[8]) * (in2[8] << 0);++  felem_reduce_degree(out, tmp);+}++static void felem_assign(felem out, const felem in) {+  memcpy(out, in, sizeof(felem));+}++/* felem_scalar_3 sets out=3*out.+ *+ * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */+static void felem_scalar_3(felem out) {+  limb carry = 0;+  unsigned i;++  for (i = 0;; i++) {+    out[i] *= 3;+    out[i] += carry;+    carry = out[i] >> 29;+    out[i] &= kBottom29Bits;++    i++;+    if (i == NLIMBS)+      break;++    out[i] *= 3;+    out[i] += carry;+    carry = out[i] >> 28;+    out[i] &= kBottom28Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_scalar_4 sets out=4*out.+ *+ * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */+static void felem_scalar_4(felem out) {+  limb carry = 0, next_carry;+  unsigned i;++  for (i = 0;; i++) {+    next_carry = out[i] >> 27;+    out[i] <<= 2;+    out[i] &= kBottom29Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 29);+    out[i] &= kBottom29Bits;++    i++;+    if (i == NLIMBS)+      break;++    next_carry = out[i] >> 26;+    out[i] <<= 2;+    out[i] &= kBottom28Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 28);+    out[i] &= kBottom28Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_scalar_8 sets out=8*out.+ *+ * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.+ * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */+static void felem_scalar_8(felem out) {+  limb carry = 0, next_carry;+  unsigned i;++  for (i = 0;; i++) {+    next_carry = out[i] >> 26;+    out[i] <<= 3;+    out[i] &= kBottom29Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 29);+    out[i] &= kBottom29Bits;++    i++;+    if (i == NLIMBS)+      break;++    next_carry = out[i] >> 25;+    out[i] <<= 3;+    out[i] &= kBottom28Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 28);+    out[i] &= kBottom28Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of+ * time depending on the value of |in|. */+static char felem_is_zero_vartime(const felem in) {+  limb carry;+  int i;+  limb tmp[NLIMBS];++  felem_assign(tmp, in);++  /* First, reduce tmp to a minimal form. */+  do {+    carry = 0;+    for (i = 0;; i++) {+      tmp[i] += carry;+      carry = tmp[i] >> 29;+      tmp[i] &= kBottom29Bits;++      i++;+      if (i == NLIMBS)+        break;++      tmp[i] += carry;+      carry = tmp[i] >> 28;+      tmp[i] &= kBottom28Bits;+    }++    felem_reduce_carry(tmp, carry);+  } while (carry);++  /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */+  return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||+         memcmp(tmp, kP, sizeof(tmp)) == 0 ||+         memcmp(tmp, k2P, sizeof(tmp)) == 0;+}+++/* Montgomery operations: */++#define kRDigits {2, 0, 0, 0xfffffffe, 0xffffffff, 0xffffffff, 0xfffffffd, 1} // 2^257 mod p256.p++#define kRInvDigits {0x80000000, 1, 0xffffffff, 0, 0x80000001, 0xfffffffe, 1, 0x7fffffff}  // 1 / 2^257 mod p256.p++static const cryptonite_p256_int kR = { kRDigits };+static const cryptonite_p256_int kRInv = { kRInvDigits };++/* to_montgomery sets out = R*in. */+static void to_montgomery(felem out, const cryptonite_p256_int* in) {+  cryptonite_p256_int in_shifted;+  int i;++  cryptonite_p256_init(&in_shifted);+  cryptonite_p256_modmul(&cryptonite_SECP256r1_p, in, 0, &kR, &in_shifted);++  for (i = 0; i < NLIMBS; i++) {+    if ((i & 1) == 0) {+      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom29Bits;+      cryptonite_p256_shr(&in_shifted, 29, &in_shifted);+    } else {+      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom28Bits;+      cryptonite_p256_shr(&in_shifted, 28, &in_shifted);+    }+  }++  cryptonite_p256_clear(&in_shifted);+}++/* from_montgomery sets out=in/R. */+static void from_montgomery(cryptonite_p256_int* out, const felem in) {+  cryptonite_p256_int result, tmp;+  int i, top;++  cryptonite_p256_init(&result);+  cryptonite_p256_init(&tmp);++  cryptonite_p256_add_d(&tmp, in[NLIMBS - 1], &result);+  for (i = NLIMBS - 2; i >= 0; i--) {+    if ((i & 1) == 0) {+      top = cryptonite_p256_shl(&result, 29, &tmp);+    } else {+      top = cryptonite_p256_shl(&result, 28, &tmp);+    }+    top |= cryptonite_p256_add_d(&tmp, in[i], &result);+  }++  cryptonite_p256_modmul(&cryptonite_SECP256r1_p, &kRInv, top, &result, out);++  cryptonite_p256_clear(&result);+  cryptonite_p256_clear(&tmp);+}
+ cbits/include64/p256/p256.h view
@@ -0,0 +1,167 @@+/*+ * Copyright 2013 The Android Open Source Project+ *+ * Redistribution and use in source and binary forms, with or without+ * modification, are permitted provided that the following conditions are met:+ *     * Redistributions of source code must retain the above copyright+ *       notice, this list of conditions and the following disclaimer.+ *     * Redistributions in binary form must reproduce the above copyright+ *       notice, this list of conditions and the following disclaimer in the+ *       documentation and/or other materials provided with the distribution.+ *     * Neither the name of Google Inc. nor the names of its contributors may+ *       be used to endorse or promote products derived from this software+ *       without specific prior written permission.+ *+ * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+ * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+ */++#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_+#define SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_++// Collection of routines manipulating 256 bit unsigned integers.+// Just enough to implement ecdsa-p256 and related algorithms.++#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++#define P256_BITSPERDIGIT 64+#define P256_NDIGITS 4+#define P256_NBYTES 32++// n' such as n * n' = -1 mod (2^64)+#define P256_MONTGOMERY_FACTOR 0xCCD1C8AAEE00BC4F++#define P256_LITERAL(lo,hi) (((uint32_t) (lo)) + (((uint64_t) (hi)) << 32))++typedef int cryptonite_p256_err;+typedef uint64_t cryptonite_p256_digit;+typedef int64_t cryptonite_p256_sdigit;+typedef __uint128_t cryptonite_p256_ddigit;+typedef __int128_t cryptonite_p256_sddigit;++// Defining cryptonite_p256_int as struct to leverage struct assigment.+typedef struct {+  cryptonite_p256_digit a[P256_NDIGITS];+} cryptonite_p256_int;++extern const cryptonite_p256_int cryptonite_SECP256r1_n;  // Curve order+extern const cryptonite_p256_int cryptonite_SECP256r1_p;  // Curve prime+extern const cryptonite_p256_int cryptonite_SECP256r1_b;  // Curve param++// Initialize a cryptonite_p256_int to zero.+void cryptonite_p256_init(cryptonite_p256_int* a);++// Clear a cryptonite_p256_int to zero.+void cryptonite_p256_clear(cryptonite_p256_int* a);++// Return bit. Index 0 is least significant.+int cryptonite_p256_get_bit(const cryptonite_p256_int* a, int index);++// b := a % MOD+void cryptonite_p256_mod(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    cryptonite_p256_int* b);++// c := a * (top_b | b) % MOD+void cryptonite_p256_modmul(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    const cryptonite_p256_digit top_b,+    const cryptonite_p256_int* b,+    cryptonite_p256_int* c);++// b := 1 / a % MOD+// MOD best be SECP256r1_n+void cryptonite_p256_modinv(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    cryptonite_p256_int* b);++// b := 1 / a % MOD+// MOD best be SECP256r1_n+// Faster than cryptonite_p256_modinv()+void cryptonite_p256_modinv_vartime(+    const cryptonite_p256_int* MOD,+    const cryptonite_p256_int* a,+    cryptonite_p256_int* b);++// b := a << (n % P256_BITSPERDIGIT)+// Returns the bits shifted out of most significant digit.+cryptonite_p256_digit cryptonite_p256_shl(const cryptonite_p256_int* a, int n, cryptonite_p256_int* b);++// b := a >> (n % P256_BITSPERDIGIT)+void cryptonite_p256_shr(const cryptonite_p256_int* a, int n, cryptonite_p256_int* b);++int cryptonite_p256_is_zero(const cryptonite_p256_int* a);+int cryptonite_p256_is_odd(const cryptonite_p256_int* a);+int cryptonite_p256_is_even(const cryptonite_p256_int* a);++// Returns -1, 0 or 1.+int cryptonite_p256_cmp(const cryptonite_p256_int* a, const cryptonite_p256_int *b);++// c: = a - b+// Returns -1 on borrow.+int cryptonite_p256_sub(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c);++// c := a + b+// Returns 1 on carry.+int cryptonite_p256_add(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c);++// c := a + (single digit)b+// Returns carry 1 on carry.+int cryptonite_p256_add_d(const cryptonite_p256_int* a, cryptonite_p256_digit b, cryptonite_p256_int* c);++// ec routines.++// {out_x,out_y} := nG+void cryptonite_p256_base_point_mul(const cryptonite_p256_int *n,+                         cryptonite_p256_int *out_x,+                         cryptonite_p256_int *out_y);++// {out_x,out_y} := n{in_x,in_y}+void cryptonite_p256_point_mul(const cryptonite_p256_int *n,+                    const cryptonite_p256_int *in_x,+                    const cryptonite_p256_int *in_y,+                    cryptonite_p256_int *out_x,+                    cryptonite_p256_int *out_y);++// {out_x,out_y} := n1G + n2{in_x,in_y}+void cryptonite_p256_points_mul_vartime(+    const cryptonite_p256_int *n1, const cryptonite_p256_int *n2,+    const cryptonite_p256_int *in_x, const cryptonite_p256_int *in_y,+    cryptonite_p256_int *out_x, cryptonite_p256_int *out_y);++// Return whether point {x,y} is on curve.+int cryptonite_p256_is_valid_point(const cryptonite_p256_int* x, const cryptonite_p256_int* y);++// Outputs big-endian binary form. No leading zero skips.+void cryptonite_p256_to_bin(const cryptonite_p256_int* src, uint8_t dst[P256_NBYTES]);++// Reads from big-endian binary form,+// thus pre-pad with leading zeros if short.+void cryptonite_p256_from_bin(const uint8_t src[P256_NBYTES], cryptonite_p256_int* dst);++#define P256_DIGITS(x) ((x)->a)+#define P256_DIGIT(x,y) ((x)->a[y])++#define P256_ZERO {{0}}+#define P256_ONE {{1}}++#ifdef __cplusplus+}+#endif++#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_
+ cbits/include64/p256/p256_gf.h view
@@ -0,0 +1,713 @@+/*+ * Copyright 2013 The Android Open Source Project+ *+ * Redistribution and use in source and binary forms, with or without+ * modification, are permitted provided that the following conditions are met:+ *     * Redistributions of source code must retain the above copyright+ *       notice, this list of conditions and the following disclaimer.+ *     * Redistributions in binary form must reproduce the above copyright+ *       notice, this list of conditions and the following disclaimer in the+ *       documentation and/or other materials provided with the distribution.+ *     * Neither the name of Google Inc. nor the names of its contributors may+ *       be used to endorse or promote products derived from this software+ *       without specific prior written permission.+ *+ * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+ * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+ */++// This is an implementation of the P256 finite field. It's written to be+// portable and still constant-time.+//+// WARNING: Implementing these functions in a constant-time manner is far from+//          obvious. Be careful when touching this code.+//+// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background.++#include <stdint.h>+#include <stdio.h>++#include <string.h>+#include <stdlib.h>++#include "p256/p256.h"++typedef uint8_t u8;+typedef uint32_t u32;+typedef uint64_t u64;+typedef int64_t s64;+typedef __uint128_t u128;++/* Our field elements are represented as five 64-bit limbs.+ *+ * The value of an felem (field element) is:+ *   x[0] + (x[1] * 2**51) + (x[2] * 2**103) + ... + (x[4] * 2**206)+ *+ * That is, each limb is alternately 51 or 52-bits wide in little-endian+ * order.+ *+ * This means that an felem hits 2**257, rather than 2**256 as we would like.+ *+ * Finally, the values stored in an felem are in Montgomery form. So the value+ * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.+ */+typedef u64 limb;+#define NLIMBS 5+typedef limb felem[NLIMBS];++static const limb kBottom51Bits = 0x7ffffffffffff;+static const limb kBottom52Bits = 0xfffffffffffff;++/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 51 and+ * 52-bit words. */+static const felem kOne = {+    2, 0xfc00000000000, 0x7ffffffffffff, 0xfff7fffffffff, 0x7ffff+};+static const felem kZero = {0};+static const felem kP = {+    0x7ffffffffffff, 0x1fffffffffff, 0, 0x4000000000, 0x3fffffffc0000+};+static const felem k2P = {+    0x7fffffffffffe, 0x3fffffffffff, 0, 0x8000000000, 0x7fffffff80000+};+/* kPrecomputed contains precomputed values to aid the calculation of scalar+ * multiples of the base point, G. It's actually two, equal length, tables+ * concatenated.+ *+ * The first table contains (x,y) felem pairs for 16 multiples of the base+ * point, G.+ *+ *   Index  |  Index (binary) | Value+ *       0  |           0000  | 0G (all zeros, omitted)+ *       1  |           0001  | G+ *       2  |           0010  | 2**64G+ *       3  |           0011  | 2**64G + G+ *       4  |           0100  | 2**128G+ *       5  |           0101  | 2**128G + G+ *       6  |           0110  | 2**128G + 2**64G+ *       7  |           0111  | 2**128G + 2**64G + G+ *       8  |           1000  | 2**192G+ *       9  |           1001  | 2**192G + G+ *      10  |           1010  | 2**192G + 2**64G+ *      11  |           1011  | 2**192G + 2**64G + G+ *      12  |           1100  | 2**192G + 2**128G+ *      13  |           1101  | 2**192G + 2**128G + G+ *      14  |           1110  | 2**192G + 2**128G + 2**64G+ *      15  |           1111  | 2**192G + 2**128G + 2**64G + G+ *+ * The second table follows the same style, but the terms are 2**32G,+ * 2**96G, 2**160G, 2**224G.+ *+ * This is ~2KB of data. */+static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {+    0x661a831522878, 0xf17fb6d805e79, 0x5889441d6ea57, 0xae33cfdb995bb, 0xc482fbb529ba,+    0x4a6af9d2aac15, 0x90e867917377c, 0x487cc962d2ae3, 0xec2a97443446e, 0x2b8ff8c52c42,+    0x45f8a2d41a576, 0xb06988d2653e4, 0x718b22c357305, 0x33fc920e79d2b, 0x17af34b0fe8db,+    0x38e17eb402f2f, 0x3382558649705, 0x47f6d48f482d1, 0x7bd42488d9b83, 0x3b247c8b86b78,+    0x4d08fc26f7778, 0x7a29a82fb2795, 0x75cd18f90d11a, 0xad8e213b0bc, 0x2d5f0142899e8,+    0x506f98098fb57, 0x2f0c98301e4aa, 0x39b30dd5cf67d, 0x9c146498ab13c, 0xa5db92df5b7b,+    0x184897fc4124a, 0xe3f73a19d8aa, 0x4e1c18e47066b, 0x27b2d4b52eaee, 0x30eac3ea10e99,+    0x4e74546e2e7d5, 0x1f4dde2d97a1d, 0x6ead0f88e1200, 0x7dec87c220f02, 0x3d08ff096310f,+    0x23e5659633ffa, 0x6ec648f08c722, 0x3172a3806ea35, 0xf6e5b681eb3c5, 0x2c3758260f89d,+    0x38dca4fd1da12, 0xf06067b78830d, 0x3194be87a068c, 0x78893c7eb602b, 0xcead60438432,+    0x6ee69a56a67ab, 0xd886f77701895, 0x67b0a4d9cee2b, 0x3586bbf3e4d53, 0x1db6f32921d93,+    0x260756ca4b366, 0x4f40e9d2039fa, 0x4f3f09f5a82bf, 0xccde2d641e8cd, 0x305a30cd2e8c5,+    0x471c235cb5439, 0xab279cd962f5a, 0x17e1fb6e2dd94, 0xfe64589800a77, 0xe8793d99775f,+    0x48c62f4e614aa, 0xbf76ef20eb2a4, 0x669c672556c, 0x24683e0eff056, 0x12252b369ab76,+    0x821de9f162d5, 0xf911ec99a95be, 0x6721f065c906b, 0x58d452035c736, 0x1f9f01a6a15,+    0x6135009b7d8d3, 0xdaeeeb417dfc0, 0x63865fea0ee17, 0x6e0a304b939d6, 0x204ba2076833d,+    0x4ade586f35669, 0x2c1077e34611a, 0x5b1a3bea3b81a, 0xf97d018a22c8b, 0x38d7996b08af8,+    0x6ea62baeb7aa0, 0xebdcbd9ef2670, 0x35dc8fe0df3fe, 0xe458309d20c24, 0x11e87898716a0,+    0x7c44bab7cb456, 0xd64d3cf1bb64, 0x189bff1bf9e66, 0xb5218a049311, 0x285dda6cbcc81,+    0x3238dcafd8c7c, 0x607736c8de0, 0xdb83d99508b1, 0x4e1a0d404cd81, 0x1588008c00ff2,+    0x16b8b36722b27, 0x876609c3f3f1a, 0x66b72ef0e17d6, 0x705f8a279d568, 0x2eaac4cd01fdd,+    0x1171ce9705fe9, 0xffc79cd3264ee, 0x700c8ab4b80f0, 0x208d3d4f57a1, 0x337262a8ca4eb,+    0x297fd01d843fd, 0xa90956fa097f8, 0x529759fdb3845, 0x1d78c5e2d0397, 0x3d6938a4adbf3,+    0x16d5853560b66, 0xf138946b9a430, 0x2ab79f4dea6a0, 0xd42053ee43ae1, 0x3b9c3ef1cf870,+    0x598934ad81baf, 0x5f1821b1d07a7, 0x416bb3a973ff3, 0x23f07bd0a047a, 0x19bdc2e09f786,+    0x56dc9981cd51f, 0xfbace23c8cd65, 0x673bd3bf5b52e, 0x46a95d229fd61, 0xe09ad64bcfb1,+    0xe5292b91f17d, 0xfeefcd8afc287, 0x58f52b0a58711, 0x4800f20c201ef, 0x2084fce608f67,+    0x12ba0b128ae0b, 0x5977ae17030b4, 0x101126ee420f6, 0xf70823495c6bd, 0xde19a27d7770,+    0x5c6ac852260e8, 0x9d22950ac4356, 0x441cca955246c, 0x660a34e5332d9, 0x14ac8ea92f8d2,+    0x6b6d7709f307e, 0x67d7e13879db, 0x2ea8626f9fbbd, 0x99609006a4b40, 0x31bb2a8f8c779,+    0x10c04828ea335, 0xae9acdcbc080a, 0x617af2342607a, 0xc7494ea53e553, 0x2ca9e2872defa,+    0x6c399fab21f1f, 0xab139b245e758, 0x3ad933dcba589, 0x4797fecb08811, 0x31f5dbf8f594,+    0x7dc6361cc7a69, 0xc8a7953ead3f9, 0x79ed693d18015, 0x418a024999a6a, 0x2c4fdc9436aa,+    0x1eb98cb06aa75, 0x2989592796a9c, 0x11194821e425, 0xe27a648228388, 0x35d834b6c12a0,+    0x541807713b532, 0x7ae0a1008aaee, 0x7017a29bcb5e, 0x6b193c23c315c, 0x19bd25ac82f2a,+    0x6a01a43eef294, 0xddf5b5fd84f19, 0x33f5ba081c016, 0xdeb052d1bc082, 0x6b2f06afa617,+    0x7ca1eda6a939f, 0xbdeb35997b50c, 0x47f2d1bccda5, 0xc2ff4adfed667, 0x87712997be4,+    0x21fc2e2b37659, 0xf7d62cd5ed951, 0x27fa9cbdf7efa, 0xba25582bf3a6b, 0x2a42b8bd89398,+    0x6d377d07eecd2, 0x9ca1df5af387, 0x1109e3427e2ba, 0xce4aa4572a19, 0x103baaef71e16,+    0x2c3b2dfde328a, 0xbec4b4a30e1ef, 0x37d92a86204f3, 0x806cfde68eb39, 0x246e2f72b8aa5,+    0x68d3de93462a9, 0x53b8acba6bbc3, 0x2492a70fa1696, 0x38c62d5760f55, 0x15096fe4904f2,+    0x4e44e9bed3e3a, 0xb28bfd79cc9bc, 0x6a77513839320, 0x480dcec6739db, 0x3601b739f2465,+    0x43c348e2a7e1, 0xe448106327879, 0x175d9cae1b0ed, 0xd3b89dee743b8, 0x392d73ca255bc,+    0x32946db0d3a18, 0x9261b09907cc, 0x5ba517a755722, 0x51f24fdaf5184, 0x1cdc732989ed8,+    0x2f7806ba16694, 0xae0c9f029f8d0, 0xd8b45102ce1, 0xca1c7db9316d6, 0x162088a67066f,+    0x39de35b2b4162, 0xa19f550d88ae9, 0x7921b27026cde, 0x94b936b66e900, 0x1023bd5fa17fc,+    0x436837814cfa4, 0x29113492283c4, 0x66d1cdd8b51d8, 0xa540702278eb2, 0x47ef1b29285d,+    0x587b50917e50e, 0xb4cda75bab3b, 0x112520b0a9886, 0x66b9ac16fee49, 0x17bf17e92b2eb,+    0x2456a2f150ed7, 0xfa214412d0280, 0x3ca7dd947fe5b, 0xa72c28598d58a, 0x255d945efc3e,+    0x2873f04e0f215, 0x74178fd1af57b, 0x788848b5b2d6, 0xb1ffafaae0db6, 0x32a1b7b3cbb2a,+    0x4bd9935d6b2da, 0x9c08f24ad30a5, 0x4e58407a80f, 0x1b3a3825a5b17, 0x6547e9fc82f5,+    0x47484aa3656c3, 0x6ee43f341a494, 0x64a98f87adea2, 0x619b3f8e95f01, 0xb6e513266ed8,+    0x421c2a673090, 0xa1c1de32348c7, 0x55b85c3a1e8a3, 0xe05ce8ef330b4, 0x2561e49c15d84,+    0x40aa2d33130fa, 0x12b827d35866f, 0xfe4cf62c8ddb, 0x2fa0ef05bb28d, 0x1c06ca63f1cb8,+    0x32a971863863b, 0xff6fc86830da1, 0x71e7b25a14cf3, 0xea9c5ebb1373a, 0x250bbaa3e1634,+    0x5b5ffeda5b765, 0xf25d2a746331b, 0x115e3a3f43632, 0x67303af43c9d5, 0x14bb538a0e559,+    0x75623687d43b7, 0xa349674a4b38d, 0x613c61829ffc6, 0x689828d8110c7, 0x139115f5af7d5,+    0xf1d856152289, 0x45cbe967168ab, 0x51f38e1680901, 0x34808e8f652b0, 0x1f4a6a921e156,+    0x35dfaf3d8341f, 0xf53ace725cb63, 0x3d86a54eef35b, 0xa103aabaffe2c, 0x2decc36296fbd,+    0x510282be73d6f, 0xd4e6365db206a, 0x4bdc5f5bb8bf3, 0xde7ea32a3aee7, 0x71269e274305,+};+++/* Field element operations: */++/* NON_ZERO_TO_ALL_ONES returns:+ *   0xffffffffffffffff for 0 < x <= 2**63+ *   0 for x == 0 or x > 2**63.+ *+ * x must be a u64 or an equivalent type such as limb. */+#define NON_ZERO_TO_ALL_ONES(x) ((((u64)(x) - 1) >> 63) - 1)++/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,+ * which is a term at 2**257.+ *+ * On entry: carry < 2**6, inout[0,2,...] < 2**51, inout[1,3,...] < 2**52.+ * On exit: inout[0,2,..] < 2**52, inout[1,3,...] < 2**53. */+static void felem_reduce_carry(felem inout, limb carry) {+  const u64 carry_mask = NON_ZERO_TO_ALL_ONES(carry);++  inout[0] += carry << 1;+  inout[1] += 0x10000000000000 & carry_mask;+  /* carry < 2**6 thus (carry << 46) < 2**52 and we added 2**52 in the+   * previous line therefore this doesn't underflow. */+  inout[1] -= carry << 46;+  inout[2] += (0x8000000000000 - 1) & carry_mask;+  inout[3] += (0x10000000000000 - 1) & carry_mask;+  inout[3] -= carry << 39;+  /* This may underflow if carry is non-zero but, if so, we'll fix it in the+   * next line. */+  inout[4] -= 1 & carry_mask;+  inout[4] += carry << 19;+}++/* felem_sum sets out = in+in2.+ *+ * On entry, in[i]+in2[i] must not overflow a 64-bit word.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53 */+static void felem_sum(felem out, const felem in, const felem in2) {+  limb carry = 0;+  unsigned i;++  for (i = 0;; i++) {+    out[i] = in[i] + in2[i];+    out[i] += carry;+    carry = out[i] >> 51;+    out[i] &= kBottom51Bits;++    i++;+    if (i == NLIMBS)+      break;++    out[i] = in[i] + in2[i];+    out[i] += carry;+    carry = out[i] >> 52;+    out[i] &= kBottom52Bits;+  }++  felem_reduce_carry(out, carry);+}++#define two53m3 (((limb)1) << 53) - (((limb)1) << 3)+#define two54m52p48m2 (((limb)1) << 54) - (((limb)1) << 52) + (((limb)1) << 48) - (((limb)1) << 2)+#define two53m2p0 (((limb)1) << 53) - (((limb)1) << 2) + (((limb)1) << 0)+#define two54m52p41m2 (((limb)1) << 54) - (((limb)1) << 52) + (((limb)1) << 41) - (((limb)1) << 2)+#define two53m21m2p0 (((limb)1) << 53) - (((limb)1) << 21) - (((limb)1) << 2) + (((limb)1) << 0)++/* zero53 is 0 mod p. */+static const felem zero53 = { two53m3, two54m52p48m2, two53m2p0, two54m52p41m2, two53m21m2p0 };++/* felem_diff sets out = in-in2.+ *+ * On entry: in[0,2,...] < 2**52, in[1,3,...] < 2**53 and+ *           in2[0,2,...] < 2**52, in2[1,3,...] < 2**53.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53. */+static void felem_diff(felem out, const felem in, const felem in2) {+  limb carry = 0;+  unsigned i;++   for (i = 0;; i++) {+    out[i] = in[i] - in2[i];+    out[i] += zero53[i];+    out[i] += carry;+    carry = out[i] >> 51;+    out[i] &= kBottom51Bits;++    i++;+    if (i == NLIMBS)+      break;++    out[i] = in[i] - in2[i];+    out[i] += zero53[i];+    out[i] += carry;+    carry = out[i] >> 52;+    out[i] &= kBottom52Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words+ * with the same 51,52,... bit positions as an felem.+ *+ * The values in felems are in Montgomery form: x*R mod p where R = 2**257.+ * Since we just multiplied two Montgomery values together, the result is+ * x*y*R*R mod p. We wish to divide by R in order for the result also to be+ * in Montgomery form.+ *+ * On entry: tmp[i] < 2**128+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53 */+static void felem_reduce_degree(felem out, u128 tmp[9]) {+   /* The following table may be helpful when reading this code:+    *+    * Limb number:   0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10+    * Width (bits):  51| 52| 51| 52| 51| 52| 51| 52| 51| 52| 51+    * Start bit:     0 | 51|103|154|206|257|309|360|412|463|515+    *   (odd phase): 0 | 52|103|155|206|258|309|361|412|464|515 */+  limb tmp2[10], carry, x, xShiftedMask;+  unsigned i;++  /* tmp contains 128-bit words with the same 51,52,51-bit positions as an+   * felem. So the top of an element of tmp might overlap with another+   * element two positions down. The following loop eliminates this+   * overlap. */+  tmp2[0] = (limb)(tmp[0] & kBottom51Bits);++  /* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>64)" to try+   * and hint to the compiler that it can do a single-word shift by selecting+   * the right register rather than doing a double-word shift and truncating+   * afterwards. */+  tmp2[1] = ((limb) tmp[0]) >> 51;+  tmp2[1] |= (((limb)(tmp[0] >> 64)) << 13) & kBottom52Bits;+  tmp2[1] += ((limb) tmp[1]) & kBottom52Bits;+  carry = tmp2[1] >> 52;+  tmp2[1] &= kBottom52Bits;++  for (i = 2; i < 9; i++) {+    tmp2[i] = ((limb)(tmp[i - 2] >> 64)) >> 39;+    tmp2[i] += ((limb)(tmp[i - 1])) >> 52;+    tmp2[i] += (((limb)(tmp[i - 1] >> 64)) << 12) & kBottom51Bits;+    tmp2[i] += ((limb) tmp[i]) & kBottom51Bits;+    tmp2[i] += carry;+    carry = tmp2[i] >> 51;+    tmp2[i] &= kBottom51Bits;++    i++;+    if (i == 9)+      break;+    tmp2[i] = ((limb)(tmp[i - 2] >> 64)) >> 39;+    tmp2[i] += ((limb)(tmp[i - 1])) >> 51;+    tmp2[i] += (((limb)(tmp[i - 1] >> 64)) << 13) & kBottom52Bits;+    tmp2[i] += ((limb) tmp[i]) & kBottom52Bits;+    tmp2[i] += carry;+    carry = tmp2[i] >> 52;+    tmp2[i] &= kBottom52Bits;+  }++  tmp2[9] = ((limb)(tmp[7] >> 64)) >> 39;+  tmp2[9] += ((limb)(tmp[8])) >> 51;+  tmp2[9] += (((limb)(tmp[8] >> 64)) << 13);+  tmp2[9] += carry;++  /* Montgomery elimination of terms.+   *+   * Since R is 2**257, we can divide by R with a bitwise shift if we can+   * ensure that the right-most 257 bits are all zero. We can make that true by+   * adding multiplies of p without affecting the value.+   *+   * So we eliminate limbs from right to left. Since the bottom 51 bits of p+   * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.+   * We can do that for 8 further limbs and then right shift to eliminate the+   * extra factor of R. */+  for (i = 0;; i += 2) {+    tmp2[i + 1] += tmp2[i] >> 51;+    x = tmp2[i] & kBottom51Bits;+    xShiftedMask = NON_ZERO_TO_ALL_ONES(x >> 1);+    tmp2[i] = 0;++    /* The bounds calculations for this loop are tricky. Each iteration of+     * the loop eliminates two words by adding values to words to their+     * right.+     *+     * The following table contains the amounts added to each word (as an+     * offset from the value of i at the top of the loop). The amounts are+     * accounted for from the first and second half of the loop separately+     * and are written as, for example, 51 to mean a value <2**51.+     *+     * Word:                   1   2   3   4   5   6+     * Added in top half:     52  44  52  37  50+     *                                    51+     *                                    51+     * Added in bottom half:      51  45  51  38  50+     *                                        52+     *                                        52+     *+     * The value that is currently offset 5 will be offset 3 for the next+     * iteration and then offset 1 for the iteration after that. Therefore+     * the total value added will be the values added at 5, 3 and 1.+     *+     * The following table accumulates these values. The sums at the bottom+     * are written as, for example, 53+45, to mean a value < 2**53+2**45.+     *+     * Word:                   1   2   3   4   5   6   7   8   9+     *                        52  44  52  37  50  50  50  50  50+     *                            51  45  51  38  37  38  37+     *                                52  51  52  51  52  51+     *                                    51  52  51  52  51+     *                                    44  52  51  52+     *                                    51  45  44+     *                                        52+     *                        ------------------------------------+     *                                53+ 53+ 54+ 52+ 53+ 52++     *                                45  44+ 50+ 51+ 52+ 50++     *                                    37  45+ 50+ 50+ 37+     *                                        38  44+ 38+     *                                            37+     *+     * So the greatest amount is added to tmp2[5]. If tmp2[5] has an initial+     * value of <2**52, then the maximum value will be < 2**54 + 2**52 + 2**50 ++     * 2**45 + 2**38, which is < 2**64, as required. */+    tmp2[i + 1] += (x << 45) & kBottom52Bits;+    tmp2[i + 2] += x >> 7;++    tmp2[i + 3] += (x << 38) & kBottom52Bits;+    tmp2[i + 4] += x >> 14;++    /* On tmp2[i + 4], when x < 2**1, the subtraction with (x << 18) will not+     * underflow because it is balanced with the (x << 50) term.  On the next+     * word tmp2[i + 5], terms with (x >> 1) and (x >> 33) are both zero and+     * there is no underflow either.+     *+     * When x >= 2**1, we add 2**51 to tmp2[i + 4] to avoid an underflow.+     * Removing 1 from tmp2[i + 5] is safe because (x >> 1) - (x >> 33) is+     * strictly positive.+     */+    tmp2[i + 4] += 0x8000000000000 & xShiftedMask;+    tmp2[i + 5] -= 1 & xShiftedMask;++    tmp2[i + 4] -= (x << 18) & kBottom51Bits;+    tmp2[i + 4] += (x << 50) & kBottom51Bits;+    tmp2[i + 5] += (x >> 1) - (x >> 33);++    if (i+1 == NLIMBS)+      break;+    tmp2[i + 2] += tmp2[i + 1] >> 52;+    x = tmp2[i + 1] & kBottom52Bits;+    xShiftedMask = NON_ZERO_TO_ALL_ONES(x >> 2);+    tmp2[i + 1] = 0;++    tmp2[i + 2] += (x << 44) & kBottom51Bits;+    tmp2[i + 3] += x >> 7;++    tmp2[i + 4] += (x << 37) & kBottom51Bits;+    tmp2[i + 5] += x >> 14;++    /* On tmp2[i + 5], when x < 2**2, the subtraction with (x << 18) will not+     * underflow because it is balanced with the (x << 50) term.  On the next+     * word tmp2[i + 6], terms with (x >> 2) and (x >> 34) are both zero and+     * there is no underflow either.+     *+     * When x >= 2**2, we add 2**52 to tmp2[i + 5] to avoid an underflow.+     * Removing 1 from tmp2[i + 6] is safe because (x >> 2) - (x >> 34) is+     * stricly positive.+     */+    tmp2[i + 5] += 0x10000000000000 & xShiftedMask;+    tmp2[i + 6] -= 1 & xShiftedMask;++    tmp2[i + 5] -= (x << 18) & kBottom52Bits;+    tmp2[i + 5] += (x << 50) & kBottom52Bits;+    tmp2[i + 6] += (x >> 2) - (x >> 34);+  }++  /* We merge the right shift with a carry chain. The words above 2**257 have+   * widths of 52,51,... which we need to correct when copying them down.  */+  carry = 0;+  for (i = 0; i < 4; i++) {+    out[i] = tmp2[i + 5];+    out[i] += carry;+    carry = out[i] >> 51;+    out[i] &= kBottom51Bits;++    i++;+    out[i] = tmp2[i + 5] << 1;+    out[i] += carry;+    carry = out[i] >> 52;+    out[i] &= kBottom52Bits;+  }++  out[4] = tmp2[9];+  out[4] += carry;+  carry = out[4] >> 51;+  out[4] &= kBottom51Bits;++  felem_reduce_carry(out, carry);+}++/* felem_square sets out=in*in.+ *+ * On entry: in[0,2,...] < 2**52, in[1,3,...] < 2**53.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53. */+static void felem_square(felem out, const felem in) {+  u128 tmp[9], x1x1, x3x3;++  x1x1 = ((u128) in[1]) * in[1];+  x3x3 = ((u128) in[3]) * in[3];++  tmp[0] = ((u128) in[0]) * (in[0] << 0);+  tmp[1] = ((u128) in[0]) * (in[1] << 1) + ((x1x1 & 1) << 51);+  tmp[2] = ((u128) in[0]) * (in[2] << 1) + (x1x1 >> 1);+  tmp[3] = ((u128) in[0]) * (in[3] << 1) ++           ((u128) in[1]) * (in[2] << 1);+  tmp[4] = ((u128) in[0]) * (in[4] << 1) ++           ((u128) in[1]) * (in[3] << 0) ++           ((u128) in[2]) * (in[2] << 0);+  tmp[5] = ((u128) in[1]) * (in[4] << 1) ++           ((u128) in[2]) * (in[3] << 1) + ((x3x3 & 1) << 51);+  tmp[6] = ((u128) in[2]) * (in[4] << 1) + (x3x3 >> 1);+  tmp[7] = ((u128) in[3]) * (in[4] << 1);+  tmp[8] = ((u128) in[4]) * (in[4] << 0);++  felem_reduce_degree(out, tmp);+}++/* felem_mul sets out=in*in2.+ *+ * On entry: in[0,2,...] < 2**52, in[1,3,...] < 2**53 and+ *           in2[0,2,...] < 2**52, in2[1,3,...] < 2**53.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53. */+static void felem_mul(felem out, const felem in, const felem in2) {+  u128 tmp[9], x1y1, x1y3, x3y1, x3y3;++  x1y1 = ((u128) in[1]) * in2[1];+  x1y3 = ((u128) in[1]) * in2[3];+  x3y1 = ((u128) in[3]) * in2[1];+  x3y3 = ((u128) in[3]) * in2[3];++  tmp[0] = ((u128) in[0]) * in2[0];+  tmp[1] = ((u128) in[0]) * in2[1] ++           ((u128) in[1]) * in2[0] + ((x1y1 & 1) << 51);+  tmp[2] = ((u128) in[0]) * in2[2] + (x1y1 >> 1) ++           ((u128) in[2]) * in2[0];+  tmp[3] = ((u128) in[0]) * in2[3] ++           ((u128) in[1]) * in2[2] ++           ((u128) in[2]) * in2[1] + ((x1y3 & 1) << 51) ++           ((u128) in[3]) * in2[0] + ((x3y1 & 1) << 51);+  tmp[4] = ((u128) in[0]) * in2[4] + (x1y3 >> 1) ++           ((u128) in[2]) * in2[2] + (x3y1 >> 1) ++           ((u128) in[4]) * in2[0];+  tmp[5] = ((u128) in[1]) * in2[4] ++           ((u128) in[2]) * in2[3] ++           ((u128) in[3]) * in2[2] ++           ((u128) in[4]) * in2[1] + ((x3y3 & 1) << 51);+  tmp[6] = ((u128) in[2]) * in2[4] + (x3y3 >> 1) ++           ((u128) in[4]) * in2[2];+  tmp[7] = ((u128) in[3]) * in2[4] ++           ((u128) in[4]) * in2[3];+  tmp[8] = ((u128) in[4]) * in2[4];++  felem_reduce_degree(out, tmp);+}++static void felem_assign(felem out, const felem in) {+  memcpy(out, in, sizeof(felem));+}++/* felem_scalar_3 sets out=3*out.+ *+ * On entry: out[0,2,...] < 2**52, out[1,3,...] < 2**53.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53. */+static void felem_scalar_3(felem out) {+  limb carry = 0;+  unsigned i;++  for (i = 0;; i++) {+    out[i] *= 3;+    out[i] += carry;+    carry = out[i] >> 51;+    out[i] &= kBottom51Bits;++    i++;+    if (i == NLIMBS)+      break;++    out[i] *= 3;+    out[i] += carry;+    carry = out[i] >> 52;+    out[i] &= kBottom52Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_scalar_4 sets out=4*out.+ *+ * On entry: out[0,2,...] < 2**52, out[1,3,...] < 2**53.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53. */+static void felem_scalar_4(felem out) {+  limb carry = 0, next_carry;+  unsigned i;++  for (i = 0;; i++) {+    next_carry = out[i] >> 49;+    out[i] <<= 2;+    out[i] &= kBottom51Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 51);+    out[i] &= kBottom51Bits;++    i++;+    if (i == NLIMBS)+      break;++    next_carry = out[i] >> 50;+    out[i] <<= 2;+    out[i] &= kBottom52Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 52);+    out[i] &= kBottom52Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_scalar_8 sets out=8*out.+ *+ * On entry: out[0,2,...] < 2**52, out[1,3,...] < 2**53.+ * On exit: out[0,2,...] < 2**52, out[1,3,...] < 2**53. */+static void felem_scalar_8(felem out) {+  limb carry = 0, next_carry;+  unsigned i;++  for (i = 0;; i++) {+    next_carry = out[i] >> 48;+    out[i] <<= 3;+    out[i] &= kBottom51Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 51);+    out[i] &= kBottom51Bits;++    i++;+    if (i == NLIMBS)+      break;++    next_carry = out[i] >> 49;+    out[i] <<= 3;+    out[i] &= kBottom52Bits;+    out[i] += carry;+    carry = next_carry + (out[i] >> 52);+    out[i] &= kBottom52Bits;+  }++  felem_reduce_carry(out, carry);+}++/* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of+ * time depending on the value of |in|. */+static char felem_is_zero_vartime(const felem in) {+  limb carry;+  int i;+  limb tmp[NLIMBS];++  felem_assign(tmp, in);++  /* First, reduce tmp to a minimal form. */+  do {+    carry = 0;+    for (i = 0;; i++) {+      tmp[i] += carry;+      carry = tmp[i] >> 51;+      tmp[i] &= kBottom51Bits;++      i++;+      if (i == NLIMBS)+        break;++      tmp[i] += carry;+      carry = tmp[i] >> 52;+      tmp[i] &= kBottom52Bits;+    }++    felem_reduce_carry(tmp, carry);+  } while (carry);++  /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */+  return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||+         memcmp(tmp, kP, sizeof(tmp)) == 0 ||+         memcmp(tmp, k2P, sizeof(tmp)) == 0;+}+++/* Montgomery operations: */++#define kRDigits {2, 0xfffffffe00000000, 0xffffffffffffffff, 0x1fffffffd} // 2^257 mod p256.p++#define kRInvDigits {0x180000000, 0xffffffff, 0xfffffffe80000001, 0x7fffffff00000001}  // 1 / 2^257 mod p256.p++static const cryptonite_p256_int kR = { kRDigits };+static const cryptonite_p256_int kRInv = { kRInvDigits };++/* to_montgomery sets out = R*in. */+static void to_montgomery(felem out, const cryptonite_p256_int* in) {+  cryptonite_p256_int in_shifted;+  int i;++  cryptonite_p256_init(&in_shifted);+  cryptonite_p256_modmul(&cryptonite_SECP256r1_p, in, 0, &kR, &in_shifted);++  for (i = 0; i < NLIMBS; i++) {+    if ((i & 1) == 0) {+      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom51Bits;+      cryptonite_p256_shr(&in_shifted, 51, &in_shifted);+    } else {+      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom52Bits;+      cryptonite_p256_shr(&in_shifted, 52, &in_shifted);+    }+  }++  cryptonite_p256_clear(&in_shifted);+}++/* from_montgomery sets out=in/R. */+static void from_montgomery(cryptonite_p256_int* out, const felem in) {+  cryptonite_p256_int result, tmp;+  int i, top;++  cryptonite_p256_init(&result);+  cryptonite_p256_init(&tmp);++  cryptonite_p256_add_d(&tmp, in[NLIMBS - 1], &result);+  for (i = NLIMBS - 2; i >= 0; i--) {+    if ((i & 1) == 0) {+      top = cryptonite_p256_shl(&result, 51, &tmp);+    } else {+      top = cryptonite_p256_shl(&result, 52, &tmp);+    }+    top += cryptonite_p256_add_d(&tmp, in[i], &result);+  }++  cryptonite_p256_modmul(&cryptonite_SECP256r1_p, &kRInv, top, &result, out);++  cryptonite_p256_clear(&result);+  cryptonite_p256_clear(&tmp);+}
cbits/p256/p256.c view
@@ -25,7 +25,7 @@  */  // This is an implementation of the P256 elliptic curve group. It's written to-// be portable 32-bit, although it's still constant-time.+// be portable and still constant-time. // // WARNING: Implementing these functions in a constant-time manner is far from //          obvious. Be careful when touching this code.@@ -40,14 +40,16 @@ #include "p256/p256.h"  const cryptonite_p256_int cryptonite_SECP256r1_n =  // curve order-  {{0xfc632551, 0xf3b9cac2, 0xa7179e84, 0xbce6faad, -1, -1, 0, -1}};+  {{P256_LITERAL(0xfc632551, 0xf3b9cac2), P256_LITERAL(0xa7179e84, 0xbce6faad),+    P256_LITERAL(-1, -1), P256_LITERAL(0, -1)}};  const cryptonite_p256_int cryptonite_SECP256r1_p =  // curve field size-  {{-1, -1, -1, 0, 0, 0, 1, -1 }};+  {{P256_LITERAL(-1, -1), P256_LITERAL(-1, 0),+    P256_LITERAL(0, 0), P256_LITERAL(1, -1) }};  const cryptonite_p256_int cryptonite_SECP256r1_b =  // curve b-  {{0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,-    0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8}};+  {{P256_LITERAL(0x27d2604b, 0x3bce3c3e), P256_LITERAL(0xcc53b0f6, 0x651d06b0),+    P256_LITERAL(0x769886bc, 0xb3ebbd55), P256_LITERAL(0xaa3a93e7, 0x5ac635d8)}};  void cryptonite_p256_init(cryptonite_p256_int* a) {   memset(a, 0, sizeof(*a));@@ -61,9 +63,10 @@ }  int cryptonite_p256_is_zero(const cryptonite_p256_int* a) {-  int i, result = 0;+  cryptonite_p256_digit result = 0;+  int i = 0;   for (i = 0; i < P256_NDIGITS; ++i) result |= P256_DIGIT(a, i);-  return !result;+  return result == 0; }  // top, c[] += a[] * b@@ -167,6 +170,10 @@     // top can be any value at this point.     // Guestimate reducer as top * MOD, since msw of MOD is -1.     top_reducer = mulAdd(MOD, top, 0, reducer);+#if P256_BITSPERDIGIT > 32+    // Correction when msw of MOD has only high 32 bits set+    top_reducer += mulAdd(MOD, top >> 32, 0, reducer);+#endif      // Subtract reducer from top | tmp.     top = subTop(top_reducer, reducer, top, tmp + i);@@ -229,7 +236,7 @@     P256_DIGIT(b, i) = accu;   }   P256_DIGIT(b, i) = (P256_DIGIT(a, i) >> 1) |-      (highbit << (P256_BITSPERDIGIT - 1));+      (((cryptonite_p256_sdigit) highbit) << (P256_BITSPERDIGIT - 1)); }  // Return -1, 0, 1 for a < b, a == b or a > b respectively.@@ -359,31 +366,32 @@ }  void cryptonite_p256_from_bin(const uint8_t src[P256_NBYTES], cryptonite_p256_int* dst) {-  int i;+  int i, n;   const uint8_t* p = &src[0];    for (i = P256_NDIGITS - 1; i >= 0; --i) {-    P256_DIGIT(dst, i) =-        (p[0] << 24) |-        (p[1] << 16) |-        (p[2] << 8) |-        p[3];-    p += 4;+    cryptonite_p256_digit dig = 0;+    n = P256_BITSPERDIGIT;+    while (n > 0) {+      n -= 8;+      dig |= ((cryptonite_p256_digit) *(p++)) << n;+    }+    P256_DIGIT(dst, i) = dig;   } }  void cryptonite_p256_to_bin(const cryptonite_p256_int* src, uint8_t dst[P256_NBYTES]) {-	int i;+	int i, n; 	uint8_t* p = &dst[0];  	for (i = P256_NDIGITS -1; i >= 0; --i) { 		const cryptonite_p256_digit dig = P256_DIGIT(src, i);-		p[0] = dig >> 24;-		p[1] = dig >> 16;-		p[2] = dig >> 8;-		p[3] = dig;-		p += 4;+		n = P256_BITSPERDIGIT;+		while (n > 0) {+			n -= 8;+			*(p++) = dig >> n;+		} 	} } @@ -395,6 +403,7 @@  // c = a + b mod MOD void cryptonite_p256e_modadd(const cryptonite_p256_int* MOD, const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c) {+  assert(c);  /* avoid repeated checks inside inlined cryptonite_p256_add */   cryptonite_p256_digit top = cryptonite_p256_add(a, b, c);   top = subM(MOD, top, P256_DIGITS(c), -1);   top = subM(MOD, top, P256_DIGITS(c), MSB_COMPLEMENT(top));@@ -403,8 +412,117 @@  // c = a - b mod MOD void cryptonite_p256e_modsub(const cryptonite_p256_int* MOD, const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c) {+  assert(c); /* avoid repeated checks inside inlined cryptonite_p256_sub */   cryptonite_p256_digit top = cryptonite_p256_sub(a, b, c);   top = addM(MOD, top, P256_DIGITS(c), ~MSB_COMPLEMENT(top));   top = subM(MOD, top, P256_DIGITS(c), MSB_COMPLEMENT(top));   addM(MOD, 0, P256_DIGITS(c), top);+}++#define NTH_DOUBLE_THEN_ADD(i, a, nth, b, out)   \+    cryptonite_p256e_montmul(a, a, out);         \+    for (i = 1; i < nth; i++)                    \+        cryptonite_p256e_montmul(out, out, out); \+    cryptonite_p256e_montmul(out, b, out);++const cryptonite_p256_int cryptonite_SECP256r1_r2 = // r^2 mod n+  {{P256_LITERAL(0xBE79EEA2, 0x83244C95), P256_LITERAL(0x49BD6FA6, 0x4699799C),+    P256_LITERAL(0x2B6BEC59, 0x2845B239), P256_LITERAL(0xF3D95620, 0x66E12D94)}};++const cryptonite_p256_int cryptonite_SECP256r1_one = {{1}};++// Montgomery multiplication, i.e. c = ab/r mod n with r = 2^256.+// Implementation is adapted from 'sc_montmul' in libdecaf.+static void cryptonite_p256e_montmul(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c) {+  int i, j, borrow;+  cryptonite_p256_digit accum[P256_NDIGITS+1] = {0};+  cryptonite_p256_digit hi_carry = 0;++  for (i=0; i<P256_NDIGITS; i++) {+    cryptonite_p256_digit mand = P256_DIGIT(a, i);+    const cryptonite_p256_digit *mier = P256_DIGITS(b);++    cryptonite_p256_ddigit chain = 0;+    for (j=0; j<P256_NDIGITS; j++) {+      chain += ((cryptonite_p256_ddigit)mand)*mier[j] + accum[j];+      accum[j] = chain;+      chain >>= P256_BITSPERDIGIT;+    }+    accum[j] = chain;++    mand = accum[0] * P256_MONTGOMERY_FACTOR;+    chain = 0;+    mier = P256_DIGITS(&cryptonite_SECP256r1_n);+    for (j=0; j<P256_NDIGITS; j++) {+      chain += (cryptonite_p256_ddigit)mand*mier[j] + accum[j];+      if (j) accum[j-1] = chain;+      chain >>= P256_BITSPERDIGIT;+    }+    chain += accum[j];+    chain += hi_carry;+    accum[j-1] = chain;+    hi_carry = chain >> P256_BITSPERDIGIT;+  }++  memcpy(P256_DIGITS(c), accum, sizeof(*c));+  borrow = cryptonite_p256_sub(c, &cryptonite_SECP256r1_n, c);+  addM(&cryptonite_SECP256r1_n, 0, P256_DIGITS(c), borrow + hi_carry);+}++// b = 1/a mod n, using Fermat's little theorem.+void cryptonite_p256e_scalar_invert(const cryptonite_p256_int* a, cryptonite_p256_int* b) {+  cryptonite_p256_int _1, _10, _11, _101, _111, _1010, _1111;+  cryptonite_p256_int _10101, _101010, _101111, x6, x8, x16, x32;+  int i;++  // Montgomerize+  cryptonite_p256e_montmul(a, &cryptonite_SECP256r1_r2, &_1);++  // P-256 (secp256r1) Scalar Inversion+  // <https://briansmith.org/ecc-inversion-addition-chains-01>+  cryptonite_p256e_montmul(&_1     , &_1     , &_10);+  cryptonite_p256e_montmul(&_10    , &_1     , &_11);+  cryptonite_p256e_montmul(&_10    , &_11    , &_101);+  cryptonite_p256e_montmul(&_10    , &_101   , &_111);+  cryptonite_p256e_montmul(&_101   , &_101   , &_1010);+  cryptonite_p256e_montmul(&_101   , &_1010  , &_1111);+  NTH_DOUBLE_THEN_ADD(i, &_1010,  1   , &_1     , &_10101);+  cryptonite_p256e_montmul(&_10101 , &_10101 , &_101010);+  cryptonite_p256e_montmul(&_101   , &_101010, &_101111);+  cryptonite_p256e_montmul(&_10101 , &_101010, &x6);+  NTH_DOUBLE_THEN_ADD(i, &x6   ,  2   , &_11    , &x8);+  NTH_DOUBLE_THEN_ADD(i, &x8   ,  8   , &x8     , &x16);+  NTH_DOUBLE_THEN_ADD(i, &x16  , 16   , &x16    , &x32);++  NTH_DOUBLE_THEN_ADD(i, &x32  , 32+32, &x32    , b);+  NTH_DOUBLE_THEN_ADD(i, b     ,    32, &x32    , b);+  NTH_DOUBLE_THEN_ADD(i, b     ,     6, &_101111, b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 3, &_111   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 2, &_11    , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 1 + 4, &_1111  , b);+  NTH_DOUBLE_THEN_ADD(i, b     ,     5, &_10101 , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 1 + 3, &_101   , b);+  NTH_DOUBLE_THEN_ADD(i, b     ,     3, &_101   , b);+  NTH_DOUBLE_THEN_ADD(i, b     ,     3, &_101   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 3, &_111   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 3 + 6, &_101111, b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 4, &_1111  , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 1 + 1, &_1     , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 4 + 1, &_1     , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 4, &_1111  , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 3, &_111   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 1 + 3, &_111   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 3, &_111   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 3, &_101   , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 1 + 2, &_11    , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 4 + 6, &_101111, b);+  NTH_DOUBLE_THEN_ADD(i, b     ,     2, &_11    , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 3 + 2, &_11    , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 3 + 2, &_11    , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 1, &_1     , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 5, &_10101 , b);+  NTH_DOUBLE_THEN_ADD(i, b     , 2 + 4, &_1111  , b);++  // Demontgomerize+  cryptonite_p256e_montmul(b, &cryptonite_SECP256r1_one, b); }
− cbits/p256/p256.h
@@ -1,162 +0,0 @@-/*- * Copyright 2013 The Android Open Source Project- *- * Redistribution and use in source and binary forms, with or without- * modification, are permitted provided that the following conditions are met:- *     * Redistributions of source code must retain the above copyright- *       notice, this list of conditions and the following disclaimer.- *     * Redistributions in binary form must reproduce the above copyright- *       notice, this list of conditions and the following disclaimer in the- *       documentation and/or other materials provided with the distribution.- *     * Neither the name of Google Inc. nor the names of its contributors may- *       be used to endorse or promote products derived from this software- *       without specific prior written permission.- *- * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO- * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.- */--#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_-#define SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_--// Collection of routines manipulating 256 bit unsigned integers.-// Just enough to implement ecdsa-p256 and related algorithms.--#include <stdint.h>--#ifdef __cplusplus-extern "C" {-#endif--#define P256_BITSPERDIGIT 32-#define P256_NDIGITS 8-#define P256_NBYTES 32--typedef int cryptonite_p256_err;-typedef uint32_t cryptonite_p256_digit;-typedef int32_t cryptonite_p256_sdigit;-typedef uint64_t cryptonite_p256_ddigit;-typedef int64_t cryptonite_p256_sddigit;--// Defining cryptonite_p256_int as struct to leverage struct assigment.-typedef struct {-  cryptonite_p256_digit a[P256_NDIGITS];-} cryptonite_p256_int;--extern const cryptonite_p256_int cryptonite_SECP256r1_n;  // Curve order-extern const cryptonite_p256_int cryptonite_SECP256r1_p;  // Curve prime-extern const cryptonite_p256_int cryptonite_SECP256r1_b;  // Curve param--// Initialize a cryptonite_p256_int to zero.-void cryptonite_p256_init(cryptonite_p256_int* a);--// Clear a cryptonite_p256_int to zero.-void cryptonite_p256_clear(cryptonite_p256_int* a);--// Return bit. Index 0 is least significant.-int cryptonite_p256_get_bit(const cryptonite_p256_int* a, int index);--// b := a % MOD-void cryptonite_p256_mod(-    const cryptonite_p256_int* MOD,-    const cryptonite_p256_int* a,-    cryptonite_p256_int* b);--// c := a * (top_b | b) % MOD-void cryptonite_p256_modmul(-    const cryptonite_p256_int* MOD,-    const cryptonite_p256_int* a,-    const cryptonite_p256_digit top_b,-    const cryptonite_p256_int* b,-    cryptonite_p256_int* c);--// b := 1 / a % MOD-// MOD best be SECP256r1_n-void cryptonite_p256_modinv(-    const cryptonite_p256_int* MOD,-    const cryptonite_p256_int* a,-    cryptonite_p256_int* b);--// b := 1 / a % MOD-// MOD best be SECP256r1_n-// Faster than cryptonite_p256_modinv()-void cryptonite_p256_modinv_vartime(-    const cryptonite_p256_int* MOD,-    const cryptonite_p256_int* a,-    cryptonite_p256_int* b);--// b := a << (n % P256_BITSPERDIGIT)-// Returns the bits shifted out of most significant digit.-cryptonite_p256_digit cryptonite_p256_shl(const cryptonite_p256_int* a, int n, cryptonite_p256_int* b);--// b := a >> (n % P256_BITSPERDIGIT)-void cryptonite_p256_shr(const cryptonite_p256_int* a, int n, cryptonite_p256_int* b);--int cryptonite_p256_is_zero(const cryptonite_p256_int* a);-int cryptonite_p256_is_odd(const cryptonite_p256_int* a);-int cryptonite_p256_is_even(const cryptonite_p256_int* a);--// Returns -1, 0 or 1.-int cryptonite_p256_cmp(const cryptonite_p256_int* a, const cryptonite_p256_int *b);--// c: = a - b-// Returns -1 on borrow.-int cryptonite_p256_sub(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c);--// c := a + b-// Returns 1 on carry.-int cryptonite_p256_add(const cryptonite_p256_int* a, const cryptonite_p256_int* b, cryptonite_p256_int* c);--// c := a + (single digit)b-// Returns carry 1 on carry.-int cryptonite_p256_add_d(const cryptonite_p256_int* a, cryptonite_p256_digit b, cryptonite_p256_int* c);--// ec routines.--// {out_x,out_y} := nG-void cryptonite_p256_base_point_mul(const cryptonite_p256_int *n,-                         cryptonite_p256_int *out_x,-                         cryptonite_p256_int *out_y);--// {out_x,out_y} := n{in_x,in_y}-void cryptonite_p256_point_mul(const cryptonite_p256_int *n,-                    const cryptonite_p256_int *in_x,-                    const cryptonite_p256_int *in_y,-                    cryptonite_p256_int *out_x,-                    cryptonite_p256_int *out_y);--// {out_x,out_y} := n1G + n2{in_x,in_y}-void cryptonite_p256_points_mul_vartime(-    const cryptonite_p256_int *n1, const cryptonite_p256_int *n2,-    const cryptonite_p256_int *in_x, const cryptonite_p256_int *in_y,-    cryptonite_p256_int *out_x, cryptonite_p256_int *out_y);--// Return whether point {x,y} is on curve.-int cryptonite_p256_is_valid_point(const cryptonite_p256_int* x, const cryptonite_p256_int* y);--// Outputs big-endian binary form. No leading zero skips.-void cryptonite_p256_to_bin(const cryptonite_p256_int* src, uint8_t dst[P256_NBYTES]);--// Reads from big-endian binary form,-// thus pre-pad with leading zeros if short.-void cryptonite_p256_from_bin(const uint8_t src[P256_NBYTES], cryptonite_p256_int* dst);--#define P256_DIGITS(x) ((x)->a)-#define P256_DIGIT(x,y) ((x)->a[y])--#define P256_ZERO {{0}}-#define P256_ONE {{1}}--#ifdef __cplusplus-}-#endif--#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_
cbits/p256/p256_ec.c view
@@ -25,580 +25,18 @@  */  // This is an implementation of the P256 elliptic curve group. It's written to-// be portable 32-bit, although it's still constant-time.+// be portable and still constant-time. // // WARNING: Implementing these functions in a constant-time manner is far from //          obvious. Be careful when touching this code. // // See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background. -#include <stdint.h>-#include <stdio.h>--#include <string.h>-#include <stdlib.h>--#include "p256/p256.h"--typedef uint8_t u8;-typedef uint32_t u32;-typedef int32_t s32;-typedef uint64_t u64;--/* Our field elements are represented as nine 32-bit limbs.- *- * The value of an felem (field element) is:- *   x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228)- *- * That is, each limb is alternately 29 or 28-bits wide in little-endian- * order.- *- * This means that an felem hits 2**257, rather than 2**256 as we would like. A- * 28, 29, ... pattern would cause us to hit 2**256, but that causes problems- * when multiplying as terms end up one bit short of a limb which would require- * much bit-shifting to correct.- *- * Finally, the values stored in an felem are in Montgomery form. So the value- * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.- */-typedef u32 limb;-#define NLIMBS 9-typedef limb felem[NLIMBS];--static const limb kBottom28Bits = 0xfffffff;-static const limb kBottom29Bits = 0x1fffffff;--/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and- * 28-bit words. */-static const felem kOne = {-    2, 0, 0, 0xffff800,-    0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff,-    0-};-static const felem kZero = {0};-static const felem kP = {-    0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff,-    0, 0, 0x200000, 0xf000000,-    0xfffffff-};-static const felem k2P = {-    0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff,-    0, 0, 0x400000, 0xe000000,-    0x1fffffff-};-/* kPrecomputed contains precomputed values to aid the calculation of scalar- * multiples of the base point, G. It's actually two, equal length, tables- * concatenated.- *- * The first table contains (x,y) felem pairs for 16 multiples of the base- * point, G.- *- *   Index  |  Index (binary) | Value- *       0  |           0000  | 0G (all zeros, omitted)- *       1  |           0001  | G- *       2  |           0010  | 2**64G- *       3  |           0011  | 2**64G + G- *       4  |           0100  | 2**128G- *       5  |           0101  | 2**128G + G- *       6  |           0110  | 2**128G + 2**64G- *       7  |           0111  | 2**128G + 2**64G + G- *       8  |           1000  | 2**192G- *       9  |           1001  | 2**192G + G- *      10  |           1010  | 2**192G + 2**64G- *      11  |           1011  | 2**192G + 2**64G + G- *      12  |           1100  | 2**192G + 2**128G- *      13  |           1101  | 2**192G + 2**128G + G- *      14  |           1110  | 2**192G + 2**128G + 2**64G- *      15  |           1111  | 2**192G + 2**128G + 2**64G + G- *- * The second table follows the same style, but the terms are 2**32G,- * 2**96G, 2**160G, 2**224G.- *- * This is ~2KB of data. */-static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {-    0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee,-    0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3,-    0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c,-    0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22,-    0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050,-    0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b,-    0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa,-    0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2,-    0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609,-    0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581,-    0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca,-    0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33,-    0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6,-    0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd,-    0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0,-    0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881,-    0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a,-    0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26,-    0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b,-    0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023,-    0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133,-    0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa,-    0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29,-    0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc,-    0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8,-    0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59,-    0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39,-    0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689,-    0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa,-    0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3,-    0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1,-    0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f,-    0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72,-    0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d,-    0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b,-    0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a,-    0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a,-    0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f,-    0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb,-    0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc,-    0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9,-    0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce,-    0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2,-    0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca,-    0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229,-    0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57,-    0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c,-    0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa,-    0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651,-    0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec,-    0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7,-    0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c,-    0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927,-    0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298,-    0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8,-    0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2,-    0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d,-    0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4,-    0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8,-    0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78,-};+#include "p256/p256_gf.h"   /* Field element operations: */ -/* NON_ZERO_TO_ALL_ONES returns:- *   0xffffffff for 0 < x <= 2**31- *   0 for x == 0 or x > 2**31.- *- * x must be a u32 or an equivalent type such as limb. */-#define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1)--/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,- * which is a term at 2**257.- *- * On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28.- * On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. */-static void felem_reduce_carry(felem inout, limb carry) {-  const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry);--  inout[0] += carry << 1;-  inout[3] += 0x10000000 & carry_mask;-  /* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the-   * previous line therefore this doesn't underflow. */-  inout[3] -= carry << 11;-  inout[4] += (0x20000000 - 1) & carry_mask;-  inout[5] += (0x10000000 - 1) & carry_mask;-  inout[6] += (0x20000000 - 1) & carry_mask;-  inout[6] -= carry << 22;-  /* This may underflow if carry is non-zero but, if so, we'll fix it in the-   * next line. */-  inout[7] -= 1 & carry_mask;-  inout[7] += carry << 25;-}--/* felem_sum sets out = in+in2.- *- * On entry, in[i]+in2[i] must not overflow a 32-bit word.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */-static void felem_sum(felem out, const felem in, const felem in2) {-  limb carry = 0;-  unsigned i;--  for (i = 0;; i++) {-    out[i] = in[i] + in2[i];-    out[i] += carry;-    carry = out[i] >> 29;-    out[i] &= kBottom29Bits;--    i++;-    if (i == NLIMBS)-      break;--    out[i] = in[i] + in2[i];-    out[i] += carry;-    carry = out[i] >> 28;-    out[i] &= kBottom28Bits;-  }--  felem_reduce_carry(out, carry);-}--#define two31m3 (((limb)1) << 31) - (((limb)1) << 3)-#define two30m2 (((limb)1) << 30) - (((limb)1) << 2)-#define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2)-#define two31m2 (((limb)1) << 31) - (((limb)1) << 2)-#define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2)-#define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2)--/* zero31 is 0 mod p. */-static const felem zero31 = { two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2 };--/* felem_diff sets out = in-in2.- *- * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and- *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */-static void felem_diff(felem out, const felem in, const felem in2) {-  limb carry = 0;-  unsigned i;--   for (i = 0;; i++) {-    out[i] = in[i] - in2[i];-    out[i] += zero31[i];-    out[i] += carry;-    carry = out[i] >> 29;-    out[i] &= kBottom29Bits;--    i++;-    if (i == NLIMBS)-      break;--    out[i] = in[i] - in2[i];-    out[i] += zero31[i];-    out[i] += carry;-    carry = out[i] >> 28;-    out[i] &= kBottom28Bits;-  }--  felem_reduce_carry(out, carry);-}--/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words- * with the same 29,28,... bit positions as an felem.- *- * The values in felems are in Montgomery form: x*R mod p where R = 2**257.- * Since we just multiplied two Montgomery values together, the result is- * x*y*R*R mod p. We wish to divide by R in order for the result also to be- * in Montgomery form.- *- * On entry: tmp[i] < 2**64- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */-static void felem_reduce_degree(felem out, u64 tmp[17]) {-   /* The following table may be helpful when reading this code:-    *-    * Limb number:   0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...-    * Width (bits):  29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29-    * Start bit:     0 | 29| 57| 86|114|143|171|200|228|257|285-    *   (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 */-  limb tmp2[18], carry, x, xMask;-  unsigned i;--  /* tmp contains 64-bit words with the same 29,28,29-bit positions as an-   * felem. So the top of an element of tmp might overlap with another-   * element two positions down. The following loop eliminates this-   * overlap. */-  tmp2[0] = (limb)(tmp[0] & kBottom29Bits);--  /* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try-   * and hint to the compiler that it can do a single-word shift by selecting-   * the right register rather than doing a double-word shift and truncating-   * afterwards. */-  tmp2[1] = ((limb) tmp[0]) >> 29;-  tmp2[1] |= (((limb)(tmp[0] >> 32)) << 3) & kBottom28Bits;-  tmp2[1] += ((limb) tmp[1]) & kBottom28Bits;-  carry = tmp2[1] >> 28;-  tmp2[1] &= kBottom28Bits;--  for (i = 2; i < 17; i++) {-    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;-    tmp2[i] += ((limb)(tmp[i - 1])) >> 28;-    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 4) & kBottom29Bits;-    tmp2[i] += ((limb) tmp[i]) & kBottom29Bits;-    tmp2[i] += carry;-    carry = tmp2[i] >> 29;-    tmp2[i] &= kBottom29Bits;--    i++;-    if (i == 17)-      break;-    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;-    tmp2[i] += ((limb)(tmp[i - 1])) >> 29;-    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 3) & kBottom28Bits;-    tmp2[i] += ((limb) tmp[i]) & kBottom28Bits;-    tmp2[i] += carry;-    carry = tmp2[i] >> 28;-    tmp2[i] &= kBottom28Bits;-  }--  tmp2[17] = ((limb)(tmp[15] >> 32)) >> 25;-  tmp2[17] += ((limb)(tmp[16])) >> 29;-  tmp2[17] += (((limb)(tmp[16] >> 32)) << 3);-  tmp2[17] += carry;--  /* Montgomery elimination of terms.-   *-   * Since R is 2**257, we can divide by R with a bitwise shift if we can-   * ensure that the right-most 257 bits are all zero. We can make that true by-   * adding multiplies of p without affecting the value.-   *-   * So we eliminate limbs from right to left. Since the bottom 29 bits of p-   * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.-   * We can do that for 8 further limbs and then right shift to eliminate the-   * extra factor of R. */-  for (i = 0;; i += 2) {-    tmp2[i + 1] += tmp2[i] >> 29;-    x = tmp2[i] & kBottom29Bits;-    xMask = NON_ZERO_TO_ALL_ONES(x);-    tmp2[i] = 0;--    /* The bounds calculations for this loop are tricky. Each iteration of-     * the loop eliminates two words by adding values to words to their-     * right.-     *-     * The following table contains the amounts added to each word (as an-     * offset from the value of i at the top of the loop). The amounts are-     * accounted for from the first and second half of the loop separately-     * and are written as, for example, 28 to mean a value <2**28.-     *-     * Word:                   3   4   5   6   7   8   9   10-     * Added in top half:     28  11      29  21  29  28-     *                                        28  29-     *                                            29-     * Added in bottom half:      29  10      28  21  28   28-     *                                            29-     *-     * The value that is currently offset 7 will be offset 5 for the next-     * iteration and then offset 3 for the iteration after that. Therefore-     * the total value added will be the values added at 7, 5 and 3.-     *-     * The following table accumulates these values. The sums at the bottom-     * are written as, for example, 29+28, to mean a value < 2**29+2**28.-     *-     * Word:                   3   4   5   6   7   8   9  10  11  12  13-     *                        28  11  10  29  21  29  28  28  28  28  28-     *                            29  28  11  28  29  28  29  28  29  28-     *                                    29  28  21  21  29  21  29  21-     *                                        10  29  28  21  28  21  28-     *                                        28  29  28  29  28  29  28-     *                                            11  10  29  10  29  10-     *                                            29  28  11  28  11-     *                                                    29      29-     *                        ---------------------------------------------     *                                                30+ 31+ 30+ 31+ 30+-     *                                                28+ 29+ 28+ 29+ 21+-     *                                                21+ 28+ 21+ 28+ 10-     *                                                10  21+ 10  21+-     *                                                    11      11-     *-     * So the greatest amount is added to tmp2[10] and tmp2[12]. If-     * tmp2[10/12] has an initial value of <2**29, then the maximum value-     * will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32,-     * as required. */-    tmp2[i + 3] += (x << 10) & kBottom28Bits;-    tmp2[i + 4] += (x >> 18);--    tmp2[i + 6] += (x << 21) & kBottom29Bits;-    tmp2[i + 7] += x >> 8;--    /* At position 200, which is the starting bit position for word 7, we-     * have a factor of 0xf000000 = 2**28 - 2**24. */-    tmp2[i + 7] += 0x10000000 & xMask;-    /* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */-    tmp2[i + 8] += (x - 1) & xMask;-    tmp2[i + 7] -= (x << 24) & kBottom28Bits;-    tmp2[i + 8] -= x >> 4;--    tmp2[i + 8] += 0x20000000 & xMask;-    tmp2[i + 8] -= x;-    tmp2[i + 8] += (x << 28) & kBottom29Bits;-    tmp2[i + 9] += ((x >> 1) - 1) & xMask;--    if (i+1 == NLIMBS)-      break;-    tmp2[i + 2] += tmp2[i + 1] >> 28;-    x = tmp2[i + 1] & kBottom28Bits;-    xMask = NON_ZERO_TO_ALL_ONES(x);-    tmp2[i + 1] = 0;--    tmp2[i + 4] += (x << 11) & kBottom29Bits;-    tmp2[i + 5] += (x >> 18);--    tmp2[i + 7] += (x << 21) & kBottom28Bits;-    tmp2[i + 8] += x >> 7;--    /* At position 199, which is the starting bit of the 8th word when-     * dealing with a context starting on an odd word, we have a factor of-     * 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th-     * word from i+1 is i+8. */-    tmp2[i + 8] += 0x20000000 & xMask;-    tmp2[i + 9] += (x - 1) & xMask;-    tmp2[i + 8] -= (x << 25) & kBottom29Bits;-    tmp2[i + 9] -= x >> 4;--    tmp2[i + 9] += 0x10000000 & xMask;-    tmp2[i + 9] -= x;-    tmp2[i + 10] += (x - 1) & xMask;-  }--  /* We merge the right shift with a carry chain. The words above 2**257 have-   * widths of 28,29,... which we need to correct when copying them down.  */-  carry = 0;-  for (i = 0; i < 8; i++) {-    /* The maximum value of tmp2[i + 9] occurs on the first iteration and-     * is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is-     * therefore safe. */-    out[i] = tmp2[i + 9];-    out[i] += carry;-    out[i] += (tmp2[i + 10] << 28) & kBottom29Bits;-    carry = out[i] >> 29;-    out[i] &= kBottom29Bits;--    i++;-    out[i] = tmp2[i + 9] >> 1;-    out[i] += carry;-    carry = out[i] >> 28;-    out[i] &= kBottom28Bits;-  }--  out[8] = tmp2[17];-  out[8] += carry;-  carry = out[8] >> 29;-  out[8] &= kBottom29Bits;--  felem_reduce_carry(out, carry);-}--/* felem_square sets out=in*in.- *- * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */-static void felem_square(felem out, const felem in) {-  u64 tmp[17];--  tmp[0] = ((u64) in[0]) * in[0];-  tmp[1] = ((u64) in[0]) * (in[1] << 1);-  tmp[2] = ((u64) in[0]) * (in[2] << 1) +-           ((u64) in[1]) * (in[1] << 1);-  tmp[3] = ((u64) in[0]) * (in[3] << 1) +-           ((u64) in[1]) * (in[2] << 1);-  tmp[4] = ((u64) in[0]) * (in[4] << 1) +-           ((u64) in[1]) * (in[3] << 2) + ((u64) in[2]) * in[2];-  tmp[5] = ((u64) in[0]) * (in[5] << 1) + ((u64) in[1]) *-           (in[4] << 1) + ((u64) in[2]) * (in[3] << 1);-  tmp[6] = ((u64) in[0]) * (in[6] << 1) + ((u64) in[1]) *-           (in[5] << 2) + ((u64) in[2]) * (in[4] << 1) +-           ((u64) in[3]) * (in[3] << 1);-  tmp[7] = ((u64) in[0]) * (in[7] << 1) + ((u64) in[1]) *-           (in[6] << 1) + ((u64) in[2]) * (in[5] << 1) +-           ((u64) in[3]) * (in[4] << 1);-  /* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60,-   * which is < 2**64 as required. */-  tmp[8] = ((u64) in[0]) * (in[8] << 1) + ((u64) in[1]) *-           (in[7] << 2) + ((u64) in[2]) * (in[6] << 1) +-           ((u64) in[3]) * (in[5] << 2) + ((u64) in[4]) * in[4];-  tmp[9] = ((u64) in[1]) * (in[8] << 1) + ((u64) in[2]) *-           (in[7] << 1) + ((u64) in[3]) * (in[6] << 1) +-           ((u64) in[4]) * (in[5] << 1);-  tmp[10] = ((u64) in[2]) * (in[8] << 1) + ((u64) in[3]) *-            (in[7] << 2) + ((u64) in[4]) * (in[6] << 1) +-            ((u64) in[5]) * (in[5] << 1);-  tmp[11] = ((u64) in[3]) * (in[8] << 1) + ((u64) in[4]) *-            (in[7] << 1) + ((u64) in[5]) * (in[6] << 1);-  tmp[12] = ((u64) in[4]) * (in[8] << 1) +-            ((u64) in[5]) * (in[7] << 2) + ((u64) in[6]) * in[6];-  tmp[13] = ((u64) in[5]) * (in[8] << 1) +-            ((u64) in[6]) * (in[7] << 1);-  tmp[14] = ((u64) in[6]) * (in[8] << 1) +-            ((u64) in[7]) * (in[7] << 1);-  tmp[15] = ((u64) in[7]) * (in[8] << 1);-  tmp[16] = ((u64) in[8]) * in[8];--  felem_reduce_degree(out, tmp);-}--/* felem_mul sets out=in*in2.- *- * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and- *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */-static void felem_mul(felem out, const felem in, const felem in2) {-  u64 tmp[17];--  tmp[0] = ((u64) in[0]) * in2[0];-  tmp[1] = ((u64) in[0]) * (in2[1] << 0) +-           ((u64) in[1]) * (in2[0] << 0);-  tmp[2] = ((u64) in[0]) * (in2[2] << 0) + ((u64) in[1]) *-           (in2[1] << 1) + ((u64) in[2]) * (in2[0] << 0);-  tmp[3] = ((u64) in[0]) * (in2[3] << 0) + ((u64) in[1]) *-           (in2[2] << 0) + ((u64) in[2]) * (in2[1] << 0) +-           ((u64) in[3]) * (in2[0] << 0);-  tmp[4] = ((u64) in[0]) * (in2[4] << 0) + ((u64) in[1]) *-           (in2[3] << 1) + ((u64) in[2]) * (in2[2] << 0) +-           ((u64) in[3]) * (in2[1] << 1) +-           ((u64) in[4]) * (in2[0] << 0);-  tmp[5] = ((u64) in[0]) * (in2[5] << 0) + ((u64) in[1]) *-           (in2[4] << 0) + ((u64) in[2]) * (in2[3] << 0) +-           ((u64) in[3]) * (in2[2] << 0) + ((u64) in[4]) *-           (in2[1] << 0) + ((u64) in[5]) * (in2[0] << 0);-  tmp[6] = ((u64) in[0]) * (in2[6] << 0) + ((u64) in[1]) *-           (in2[5] << 1) + ((u64) in[2]) * (in2[4] << 0) +-           ((u64) in[3]) * (in2[3] << 1) + ((u64) in[4]) *-           (in2[2] << 0) + ((u64) in[5]) * (in2[1] << 1) +-           ((u64) in[6]) * (in2[0] << 0);-  tmp[7] = ((u64) in[0]) * (in2[7] << 0) + ((u64) in[1]) *-           (in2[6] << 0) + ((u64) in[2]) * (in2[5] << 0) +-           ((u64) in[3]) * (in2[4] << 0) + ((u64) in[4]) *-           (in2[3] << 0) + ((u64) in[5]) * (in2[2] << 0) +-           ((u64) in[6]) * (in2[1] << 0) +-           ((u64) in[7]) * (in2[0] << 0);-  /* tmp[8] has the greatest value but doesn't overflow. See logic in-   * felem_square. */-  tmp[8] = ((u64) in[0]) * (in2[8] << 0) + ((u64) in[1]) *-           (in2[7] << 1) + ((u64) in[2]) * (in2[6] << 0) +-           ((u64) in[3]) * (in2[5] << 1) + ((u64) in[4]) *-           (in2[4] << 0) + ((u64) in[5]) * (in2[3] << 1) +-           ((u64) in[6]) * (in2[2] << 0) + ((u64) in[7]) *-           (in2[1] << 1) + ((u64) in[8]) * (in2[0] << 0);-  tmp[9] = ((u64) in[1]) * (in2[8] << 0) + ((u64) in[2]) *-           (in2[7] << 0) + ((u64) in[3]) * (in2[6] << 0) +-           ((u64) in[4]) * (in2[5] << 0) + ((u64) in[5]) *-           (in2[4] << 0) + ((u64) in[6]) * (in2[3] << 0) +-           ((u64) in[7]) * (in2[2] << 0) +-           ((u64) in[8]) * (in2[1] << 0);-  tmp[10] = ((u64) in[2]) * (in2[8] << 0) + ((u64) in[3]) *-            (in2[7] << 1) + ((u64) in[4]) * (in2[6] << 0) +-            ((u64) in[5]) * (in2[5] << 1) + ((u64) in[6]) *-            (in2[4] << 0) + ((u64) in[7]) * (in2[3] << 1) +-            ((u64) in[8]) * (in2[2] << 0);-  tmp[11] = ((u64) in[3]) * (in2[8] << 0) + ((u64) in[4]) *-            (in2[7] << 0) + ((u64) in[5]) * (in2[6] << 0) +-            ((u64) in[6]) * (in2[5] << 0) + ((u64) in[7]) *-            (in2[4] << 0) + ((u64) in[8]) * (in2[3] << 0);-  tmp[12] = ((u64) in[4]) * (in2[8] << 0) + ((u64) in[5]) *-            (in2[7] << 1) + ((u64) in[6]) * (in2[6] << 0) +-            ((u64) in[7]) * (in2[5] << 1) +-            ((u64) in[8]) * (in2[4] << 0);-  tmp[13] = ((u64) in[5]) * (in2[8] << 0) + ((u64) in[6]) *-            (in2[7] << 0) + ((u64) in[7]) * (in2[6] << 0) +-            ((u64) in[8]) * (in2[5] << 0);-  tmp[14] = ((u64) in[6]) * (in2[8] << 0) + ((u64) in[7]) *-            (in2[7] << 1) + ((u64) in[8]) * (in2[6] << 0);-  tmp[15] = ((u64) in[7]) * (in2[8] << 0) +-            ((u64) in[8]) * (in2[7] << 0);-  tmp[16] = ((u64) in[8]) * (in2[8] << 0);--  felem_reduce_degree(out, tmp);-}--static void felem_assign(felem out, const felem in) {-  memcpy(out, in, sizeof(felem));-}- /* felem_inv calculates |out| = |in|^{-1}  *  * Based on Fermat's Little Theorem:@@ -667,131 +105,7 @@   felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */ } -/* felem_scalar_3 sets out=3*out.- *- * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */-static void felem_scalar_3(felem out) {-  limb carry = 0;-  unsigned i; -  for (i = 0;; i++) {-    out[i] *= 3;-    out[i] += carry;-    carry = out[i] >> 29;-    out[i] &= kBottom29Bits;--    i++;-    if (i == NLIMBS)-      break;--    out[i] *= 3;-    out[i] += carry;-    carry = out[i] >> 28;-    out[i] &= kBottom28Bits;-  }--  felem_reduce_carry(out, carry);-}--/* felem_scalar_4 sets out=4*out.- *- * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */-static void felem_scalar_4(felem out) {-  limb carry = 0, next_carry;-  unsigned i;--  for (i = 0;; i++) {-    next_carry = out[i] >> 27;-    out[i] <<= 2;-    out[i] &= kBottom29Bits;-    out[i] += carry;-    carry = next_carry + (out[i] >> 29);-    out[i] &= kBottom29Bits;--    i++;-    if (i == NLIMBS)-      break;--    next_carry = out[i] >> 26;-    out[i] <<= 2;-    out[i] &= kBottom28Bits;-    out[i] += carry;-    carry = next_carry + (out[i] >> 28);-    out[i] &= kBottom28Bits;-  }--  felem_reduce_carry(out, carry);-}--/* felem_scalar_8 sets out=8*out.- *- * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.- * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */-static void felem_scalar_8(felem out) {-  limb carry = 0, next_carry;-  unsigned i;--  for (i = 0;; i++) {-    next_carry = out[i] >> 26;-    out[i] <<= 3;-    out[i] &= kBottom29Bits;-    out[i] += carry;-    carry = next_carry + (out[i] >> 29);-    out[i] &= kBottom29Bits;--    i++;-    if (i == NLIMBS)-      break;--    next_carry = out[i] >> 25;-    out[i] <<= 3;-    out[i] &= kBottom28Bits;-    out[i] += carry;-    carry = next_carry + (out[i] >> 28);-    out[i] &= kBottom28Bits;-  }--  felem_reduce_carry(out, carry);-}--/* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of- * time depending on the value of |in|. */-static char felem_is_zero_vartime(const felem in) {-  limb carry;-  int i;-  limb tmp[NLIMBS];--  felem_assign(tmp, in);--  /* First, reduce tmp to a minimal form. */-  do {-    carry = 0;-    for (i = 0;; i++) {-      tmp[i] += carry;-      carry = tmp[i] >> 29;-      tmp[i] &= kBottom29Bits;--      i++;-      if (i == NLIMBS)-        break;--      tmp[i] += carry;-      carry = tmp[i] >> 28;-      tmp[i] &= kBottom28Bits;-    }--    felem_reduce_carry(tmp, carry);-  } while (carry);--  /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */-  return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||-         memcmp(tmp, kP, sizeof(tmp)) == 0 ||-         memcmp(tmp, k2P, sizeof(tmp)) == 0;-}-- /* Group operations:  *  * Elements of the elliptic curve group are represented in Jacobian@@ -971,9 +285,9 @@   felem_diff(y_out, y_out, tmp); } -/* copy_conditional sets out=in if mask = 0xffffffff in constant time.+/* copy_conditional sets out=in if mask = -1 in constant time.  *- * On entry: mask is either 0 or 0xffffffff. */+ * On entry: mask is either 0 or -1. */ static void copy_conditional(felem out, const felem in, limb mask) {   int i; @@ -1168,58 +482,6 @@   } } -#define kRDigits {2, 0, 0, 0xfffffffe, 0xffffffff, 0xffffffff, 0xfffffffd, 1} // 2^257 mod p256.p--#define kRInvDigits {0x80000000, 1, 0xffffffff, 0, 0x80000001, 0xfffffffe, 1, 0x7fffffff}  // 1 / 2^257 mod p256.p--static const cryptonite_p256_int kR = { kRDigits };-static const cryptonite_p256_int kRInv = { kRInvDigits };--/* to_montgomery sets out = R*in. */-static void to_montgomery(felem out, const cryptonite_p256_int* in) {-  cryptonite_p256_int in_shifted;-  int i;--  cryptonite_p256_init(&in_shifted);-  cryptonite_p256_modmul(&cryptonite_SECP256r1_p, in, 0, &kR, &in_shifted);--  for (i = 0; i < NLIMBS; i++) {-    if ((i & 1) == 0) {-      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom29Bits;-      cryptonite_p256_shr(&in_shifted, 29, &in_shifted);-    } else {-      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom28Bits;-      cryptonite_p256_shr(&in_shifted, 28, &in_shifted);-    }-  }--  cryptonite_p256_clear(&in_shifted);-}--/* from_montgomery sets out=in/R. */-static void from_montgomery(cryptonite_p256_int* out, const felem in) {-  cryptonite_p256_int result, tmp;-  int i, top;--  cryptonite_p256_init(&result);-  cryptonite_p256_init(&tmp);--  cryptonite_p256_add_d(&tmp, in[NLIMBS - 1], &result);-  for (i = NLIMBS - 2; i >= 0; i--) {-    if ((i & 1) == 0) {-      top = cryptonite_p256_shl(&result, 29, &tmp);-    } else {-      top = cryptonite_p256_shl(&result, 28, &tmp);-    }-    top |= cryptonite_p256_add_d(&tmp, in[i], &result);-  }--  cryptonite_p256_modmul(&cryptonite_SECP256r1_p, &kRInv, top, &result, out);--  cryptonite_p256_clear(&result);-  cryptonite_p256_clear(&tmp);-}- /* cryptonite_p256_base_point_mul sets {out_x,out_y} = nG, where n is < the  * order of the group. */ void cryptonite_p256_base_point_mul(const cryptonite_p256_int* n, cryptonite_p256_int* out_x, cryptonite_p256_int* out_y) {@@ -1287,19 +549,16 @@     const cryptonite_p256_int *in_x2, const cryptonite_p256_int *in_y2,     cryptonite_p256_int *out_x, cryptonite_p256_int *out_y) {-    felem x1, y1, z1, x2, y2, z2, px1, py1, px2, py2;-    const cryptonite_p256_int one = P256_ONE;+    felem x, y, z, px1, py1, px2, py2;      to_montgomery(px1, in_x1);     to_montgomery(py1, in_y1);     to_montgomery(px2, in_x2);     to_montgomery(py2, in_y2); -    scalar_mult(x1, y1, z1, px1, py1, &one);-    scalar_mult(x2, y2, z2, px2, py2, &one);-    point_add_or_double_vartime(x1, y1, z1, x1, y1, z1, x2, y2, z2);+    point_add_or_double_vartime(x, y, z, px1, py1, kOne, px2, py2, kOne); -    point_to_affine(px1, py1, x1, y1, z1);+    point_to_affine(px1, py1, x, y, z);     from_montgomery(out_x, px1);     from_montgomery(out_y, py1); }@@ -1313,4 +572,21 @@ {     memcpy(out_x, in_x, P256_NBYTES);     cryptonite_p256_sub(&cryptonite_SECP256r1_p, in_y, out_y);+}++/* this function is not part of the original source+   cryptonite_p256e_point_mul sets {out_x,out_y} = n*{in_x,in_y}, where+   n is < the order of the group.+ */+void cryptonite_p256e_point_mul(const cryptonite_p256_int* n,+    const cryptonite_p256_int* in_x, const cryptonite_p256_int* in_y,+    cryptonite_p256_int* out_x, cryptonite_p256_int* out_y) {+  felem x, y, z, px, py;++  to_montgomery(px, in_x);+  to_montgomery(py, in_y);+  scalar_mult(x, y, z, px, py, n);+  point_to_affine(px, py, x, y, z);+  from_montgomery(out_x, px);+  from_montgomery(out_y, py); }
cryptonite.cabal view
@@ -1,5 +1,5 @@ Name:                cryptonite-version:             0.26+version:             0.27 Synopsis:            Cryptography Primitives sink Description:     A repository of cryptographic primitives.@@ -19,7 +19,7 @@     * 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 strive to be a+    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.@@ -36,7 +36,7 @@ Homepage:            https://github.com/haskell-crypto/cryptonite Bug-reports:         https://github.com/haskell-crypto/cryptonite/issues Cabal-Version:       1.18-tested-with:         GHC==8.6.5, GHC==8.4.4, GHC==8.2.2, GHC==8.0.2+tested-with:         GHC==8.8.2, GHC==8.6.5, GHC==8.4.4, GHC==8.2.2, GHC==8.0.2 extra-doc-files:     README.md CHANGELOG.md extra-source-files:  cbits/*.h                      cbits/aes/*.h@@ -50,7 +50,8 @@                      cbits/decaf/p448/*.h                      cbits/decaf/ed448goldilocks/decaf_tables.c                      cbits/decaf/ed448goldilocks/decaf.c-                     cbits/p256/*.h+                     cbits/include32/p256/*.h+                     cbits/include64/p256/*.h                      cbits/blake2/ref/*.h                      cbits/blake2/sse/*.h                      cbits/argon2/*.h@@ -102,8 +103,14 @@   Default:           False   Manual:            True +Flag use_target_attributes+  Description:       use GCC / clang function attributes instead of global target options.+  Default:           True+  Manual:            True+ Library   Exposed-modules:   Crypto.Cipher.AES+                     Crypto.Cipher.AESGCMSIV                      Crypto.Cipher.Blowfish                      Crypto.Cipher.CAST5                      Crypto.Cipher.Camellia@@ -158,6 +165,7 @@                      Crypto.PubKey.ECC.ECDSA                      Crypto.PubKey.ECC.P256                      Crypto.PubKey.ECC.Types+                     Crypto.PubKey.ECDSA                      Crypto.PubKey.ECIES                      Crypto.PubKey.Ed25519                      Crypto.PubKey.Ed448@@ -177,6 +185,7 @@                      Crypto.Random.Entropy                      Crypto.Random.EntropyPool                      Crypto.Random.Entropy.Unsafe+                     Crypto.System.CPU                      Crypto.Tutorial   Other-modules:     Crypto.Cipher.AES.Primitive                      Crypto.Cipher.Blowfish.Box@@ -282,6 +291,11 @@                    , cbits/decaf/p448    if arch(x86_64) || arch(aarch64)+    include-dirs:      cbits/include64+  else+    include-dirs:      cbits/include32++  if arch(x86_64) || arch(aarch64)     C-sources:         cbits/decaf/p448/arch_ref64/f_impl.c                      , cbits/decaf/p448/f_generic.c                      , cbits/decaf/p448/f_arithmetic.c@@ -327,9 +341,13 @@     c-sources:      cbits/cryptonite_rdrand.c    if flag(support_aesni) && (os(linux) || os(freebsd) || os(osx)) && (arch(i386) || arch(x86_64))-    CC-options:     -mssse3 -maes -DWITH_AESNI+    CC-options:     -DWITH_AESNI+    if !flag(use_target_attributes)+      CC-options:     -mssse3 -maes     if flag(support_pclmuldq)-       CC-options:  -msse4.1 -mpclmul -DWITH_PCLMUL+      CC-options:   -DWITH_PCLMUL+      if !flag(use_target_attributes)+        CC-options:     -msse4.1 -mpclmul     C-sources:       cbits/aes/x86ni.c                    , cbits/aes/generic.c                    , cbits/aes/gf.c@@ -354,6 +372,8 @@    if arch(x86_64) || flag(support_sse)     CPP-options:    -DSUPPORT_SSE+    if arch(i386)+      CC-options:   -msse2    C-sources:      cbits/argon2/argon2.c   include-dirs:   cbits/argon2@@ -374,6 +394,8 @@     Build-depends:   deepseq   if flag(check_alignment)     cc-options:     -DWITH_ASSERT_ALIGNMENT+  if flag(use_target_attributes)+    cc-options:     -DWITH_TARGET_ATTRIBUTES  Test-Suite test-cryptonite   type:              exitcode-stdio-1.0@@ -385,6 +407,7 @@                      BCryptPBKDF                      ECC                      ECC.Edwards25519+                     ECDSA                      Hash                      Imports                      KAT_AES.KATCBC@@ -394,6 +417,7 @@                      KAT_AES.KATOCB3                      KAT_AES.KATXTS                      KAT_AES+                     KAT_AESGCMSIV                      KAT_AFIS                      KAT_Argon2                      KAT_Blowfish
tests/ECC.hs view
@@ -24,6 +24,19 @@         , Curve ECC.Curve_X448         ] +data CurveArith = forall curve. (ECC.EllipticCurveBasepointArith curve, Show curve) => CurveArith curve++instance Show CurveArith where+    showsPrec d (CurveArith curve) = showsPrec d curve++instance Arbitrary CurveArith where+    arbitrary = elements+        [ CurveArith ECC.Curve_P256R1+        , CurveArith ECC.Curve_P384R1+        , CurveArith ECC.Curve_P521R1+        , CurveArith ECC.Curve_Edwards25519+        ]+ data VectorPoint = VectorPoint     { vpCurve :: Curve     , vpHex   :: ByteString@@ -262,13 +275,13 @@ cryptoError :: CryptoFailable a -> Maybe CryptoError cryptoError = onCryptoFailure Just (const Nothing) -doPointDecodeTest (i, vector) =+doPointDecodeTest i vector =     case vpCurve vector of         Curve curve ->             let prx = Just curve -- using Maybe as Proxy              in testCase (show i) (vpError vector @=? cryptoError (ECC.decodePoint prx $ vpEncodedPoint vector)) -doWeakPointECDHTest (i, vector) =+doWeakPointECDHTest i vector =     case vpCurve vector of         Curve curve -> testCase (show i) $ do             let prx = Just curve -- using Maybe as Proxy@@ -277,10 +290,10 @@             vpError vector @=? cryptoError (ECC.ecdh prx (ECC.keypairGetPrivate keyPair) public)  tests = testGroup "ECC"-    [ testGroup "decodePoint" $ map doPointDecodeTest (zip [katZero..] vectorsPoint)-    , testGroup "ECDH weak points" $ map doWeakPointECDHTest (zip [katZero..] vectorsWeakPoint)+    [ testGroup "decodePoint" $ zipWith doPointDecodeTest [katZero..] vectorsPoint+    , testGroup "ECDH weak points" $ zipWith doWeakPointECDHTest [katZero..] vectorsWeakPoint     , testGroup "property"-        [ testProperty "decodePoint.encodePoint==id" $ \testDRG (Curve curve) -> do+        [ testProperty "decodePoint.encodePoint==id" $ \testDRG (Curve curve) ->             let prx = Just curve -- using Maybe as Proxy                 keyPair = withTestDRG testDRG $ ECC.curveGenerateKeyPair prx                 p1 = ECC.keypairGetPublic keyPair@@ -298,5 +311,33 @@                 bobShared'   = ECC.ecdhRaw prx (ECC.keypairGetPrivate bob) (ECC.keypairGetPublic alice)              in aliceShared == bobShared && aliceShared == CryptoPassed aliceShared'                                          && bobShared   == CryptoPassed bobShared'+        , testProperty "decodeScalar.encodeScalar==id" $ \testDRG (CurveArith curve) ->+            let prx = Just curve -- using Maybe as Proxy+                s1 = withTestDRG testDRG $ ECC.curveGenerateScalar prx+                bs = ECC.encodeScalar prx s1 :: ByteString+                s2 = ECC.decodeScalar prx bs+             in CryptoPassed s1 == s2+        , testProperty "scalarFromInteger.scalarToInteger==id" $ \testDRG (CurveArith curve) ->+            let prx = Just curve -- using Maybe as Proxy+                s1 = withTestDRG testDRG $ ECC.curveGenerateScalar prx+                bs = ECC.scalarToInteger prx s1+                s2 = ECC.scalarFromInteger prx bs+             in CryptoPassed s1 == s2+        , localOption (QuickCheckTests 20) $ testProperty "(a + b).P = a.P + b.P" $ \testDRG (CurveArith curve) ->+            let prx = Just curve -- using Maybe as Proxy+                (s, a, b) = withTestDRG testDRG $+                                (,,) <$> ECC.curveGenerateScalar prx+                                     <*> ECC.curveGenerateScalar prx+                                     <*> ECC.curveGenerateScalar prx+                p = ECC.pointBaseSmul prx s+             in ECC.pointSmul prx (ECC.scalarAdd prx a b) p == ECC.pointAdd prx (ECC.pointSmul prx a p) (ECC.pointSmul prx b p)+        , localOption (QuickCheckTests 20) $ testProperty "(a * b).P = a.(b.P)" $ \testDRG (CurveArith curve) ->+            let prx = Just curve -- using Maybe as Proxy+                (s, a, b) = withTestDRG testDRG $+                                (,,) <$> ECC.curveGenerateScalar prx+                                     <*> ECC.curveGenerateScalar prx+                                     <*> ECC.curveGenerateScalar prx+                p = ECC.pointBaseSmul prx s+             in ECC.pointSmul prx (ECC.scalarMul prx a b) p == ECC.pointSmul prx a (ECC.pointSmul prx b p)         ]     ]
+ tests/ECDSA.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE FlexibleContexts #-}+module ECDSA (tests) where++import qualified Crypto.ECC as ECDSA+import qualified Crypto.PubKey.ECC.ECDSA as ECC+import qualified Crypto.PubKey.ECC.Types as ECC+import qualified Crypto.PubKey.ECDSA as ECDSA+import Crypto.Hash.Algorithms+import Crypto.Error+import qualified Data.ByteString as B++import Imports++data Curve = forall curve. (ECDSA.EllipticCurveECDSA curve, Show (ECDSA.Scalar curve)) => Curve curve ECC.Curve ECC.CurveName++instance Show Curve where+    showsPrec d (Curve _ _ name) = showsPrec d name++instance Arbitrary Curve where+    arbitrary = elements+        [ makeCurve ECDSA.Curve_P256R1 ECC.SEC_p256r1+        , makeCurve ECDSA.Curve_P384R1 ECC.SEC_p384r1+        , makeCurve ECDSA.Curve_P521R1 ECC.SEC_p521r1+        ]+      where+        makeCurve c name = Curve c (ECC.getCurveByName name) name++arbitraryScalar curve = choose (1, n - 1)+  where n = ECC.ecc_n (ECC.common_curve curve)++sigECCToECDSA :: ECDSA.EllipticCurveECDSA curve+              => proxy curve -> ECC.Signature -> ECDSA.Signature curve+sigECCToECDSA prx (ECC.Signature r s) =+    ECDSA.Signature (throwCryptoError $ ECDSA.scalarFromInteger prx r)+                    (throwCryptoError $ ECDSA.scalarFromInteger prx s)++tests = localOption (QuickCheckTests 5) $ testGroup "ECDSA"+    [ testProperty "SHA1"   $ propertyECDSA SHA1+    , testProperty "SHA224" $ propertyECDSA SHA224+    , testProperty "SHA256" $ propertyECDSA SHA256+    , testProperty "SHA384" $ propertyECDSA SHA384+    , testProperty "SHA512" $ propertyECDSA SHA512+    ]+  where+    propertyECDSA hashAlg (Curve c curve _) (ArbitraryBS0_2901 msg) = do+        d    <- arbitraryScalar curve+        kECC <- arbitraryScalar curve+        let privECC   = ECC.PrivateKey curve d+            prx       = Just c -- using Maybe as Proxy+            kECDSA    = throwCryptoError $ ECDSA.scalarFromInteger prx kECC+            privECDSA = throwCryptoError $ ECDSA.scalarFromInteger prx d+            pubECDSA  = ECDSA.toPublic prx privECDSA+            Just sigECC   = ECC.signWith kECC privECC hashAlg msg+            Just sigECDSA = ECDSA.signWith prx kECDSA privECDSA hashAlg msg+            sigECDSA' = sigECCToECDSA prx sigECC+            msg' = msg `B.append` B.singleton 42+        return $ propertyHold [ eqTest "signature" sigECDSA sigECDSA'+                              , eqTest "verification" True (ECDSA.verify prx hashAlg pubECDSA sigECDSA' msg)+                              , eqTest "alteration"  False (ECDSA.verify prx hashAlg pubECDSA sigECDSA msg')+                              ]
tests/KAT_AES/KATGCM.hs view
@@ -56,6 +56,14 @@         , {-out = -}"\xe4\x42\xf8\xc4\xc6\x67\x84\x86\x4a\x5a\x6e\xc7\xe0\xca\x68\xac\x16\xbc\x5b\xbf\xf7\xd5\xf3\xfa\xf3\xb2\xcb\xb0\xa2\x14\xa1"         , {-taglen = -}16         , {-tag = -}"\x94\xd1\x47\xc3\xa2\xca\x93\xe9\x66\x93\x1e\x3b\xb3\xbb\x67\x01")+    -- vector 6 tests 32-bit counter wrapping+    ,   ( {-key = -}"\x01\x02\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , {-iv = -}"\xe8\x38\x84\x1d\x75\xae\x33\xb5\x4b\x51\x57\x89\xc9\x5f\xbe\x65"+        , {-aad = -}"\x54\x68\x65\x20\x66\x69\x76\x65\x20\x62\x6f\x78\x69\x6e\x67\x20\x77\x69\x7a\x61\x72\x64\x73\x20\x6a\x75\x6d\x70\x20\x71\x75\x69\x63\x6b\x6c\x79\x2e"+        , {-input = -}"\x54\x68\x65\x20\x71\x75\x69\x63\x6b\x20\x62\x72\x6f\x77\x6e\x20\x66\x6f\x78\x20\x6a\x75\x6d\x70\x73\x20\x6f\x76\x65\x72\x20\x74\x68\x65\x20\x6c\x61\x7a\x79\x20\x64\x6f\x67"+        , {-out = -}"\x82\x31\x9e\x5a\x6a\x7f\x43\xd0\x42\x8c\xf1\x01\xcf\x0c\x75\xf1\x5d\xda\x4f\xa1\x28\x95\xcd\xd7\x7b\xd5\x42\x68\x2f\xcd\x10\x1b\x0c\x75\x05\x54\xf4\x2f\x2b\xf6\x69\x96\x29"+        , {-taglen = -}16+        , {-tag = -}"\x9a\xfa\xf4\xea\xae\x2e\x6f\x40\x00\xf4\x89\x77\xd0\x1e\xd5\x14")     ]  vectors_aes256_enc :: [KATGCM]
+ tests/KAT_AESGCMSIV.hs view
@@ -0,0 +1,494 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE Rank2Types #-}+{-# LANGUAGE RecordWildCards #-}+module KAT_AESGCMSIV (tests) where++import Imports++import Data.Proxy+import qualified Data.ByteArray as B++import Crypto.Cipher.AES+import Crypto.Cipher.AESGCMSIV+import Crypto.Cipher.Types+import Crypto.Error++data Vector c = Vector+    { vecPlaintext  :: ByteString+    , vecAAD        :: ByteString+    , vecKey        :: ByteString+    , vecNonce      :: ByteString+    , vecTag        :: ByteString+    , vecCiphertext :: ByteString+    }++vecCipher :: Cipher c => Vector c -> c+vecCipher = throwCryptoError . cipherInit . vecKey++vectors128 :: [Vector AES128]+vectors128 =+    [ Vector+        { vecPlaintext  = ""+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xdc\x20\xe2\xd8\x3f\x25\x70\x5b\xb4\x9e\x43\x9e\xca\x56\xde\x25"+        , vecCiphertext = ""+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x57\x87\x82\xff\xf6\x01\x3b\x81\x5b\x28\x7c\x22\x49\x3a\x36\x4c"+        , vecCiphertext = "\xb5\xd8\x39\x33\x0a\xc7\xb7\x86"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xa4\x97\x8d\xb3\x57\x39\x1a\x0b\xc4\xfd\xec\x8b\x0d\x10\x66\x39"+        , vecCiphertext = "\x73\x23\xea\x61\xd0\x59\x32\x26\x00\x47\xd9\x42"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x30\x3a\xaf\x90\xf6\xfe\x21\x19\x9c\x60\x68\x57\x74\x37\xa0\xc4"+        , vecCiphertext = "\x74\x3f\x7c\x80\x77\xab\x25\xf8\x62\x4e\x2e\x94\x85\x79\xcf\x77"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x1a\x8e\x45\xdc\xd4\x57\x8c\x66\x7c\xd8\x68\x47\xbf\x61\x55\xff"+        , vecCiphertext = "\x84\xe0\x7e\x62\xba\x83\xa6\x58\x54\x17\x24\x5d\x7e\xc4\x13\xa9\xfe\x42\x7d\x63\x15\xc0\x9b\x57\xce\x45\xf2\xe3\x93\x6a\x94\x45"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x5e\x6e\x31\x1d\xbf\x39\x5d\x35\xb0\xfe\x39\xc2\x71\x43\x88\xf8"+        , vecCiphertext = "\x3f\xd2\x4c\xe1\xf5\xa6\x7b\x75\xbf\x23\x51\xf1\x81\xa4\x75\xc7\xb8\x00\xa5\xb4\xd3\xdc\xf7\x01\x06\xb1\xee\xa8\x2f\xa1\xd6\x4d\xf4\x2b\xf7\x22\x61\x22\xfa\x92\xe1\x7a\x40\xee\xaa\xc1\x20\x1b"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x8a\x26\x3d\xd3\x17\xaa\x88\xd5\x6b\xdf\x39\x36\xdb\xa7\x5b\xb8"+        , vecCiphertext = "\x24\x33\x66\x8f\x10\x58\x19\x0f\x6d\x43\xe3\x60\xf4\xf3\x5c\xd8\xe4\x75\x12\x7c\xfc\xa7\x02\x8e\xa8\xab\x5c\x20\xf7\xab\x2a\xf0\x25\x16\xa2\xbd\xcb\xc0\x8d\x52\x1b\xe3\x7f\xf2\x8c\x15\x2b\xba\x36\x69\x7f\x25\xb4\xcd\x16\x9c\x65\x90\xd1\xdd\x39\x56\x6d\x3f"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x3b\x0a\x1a\x25\x60\x96\x9c\xdf\x79\x0d\x99\x75\x9a\xbd\x15\x08"+        , vecCiphertext = "\x1e\x6d\xab\xa3\x56\x69\xf4\x27"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x08\x29\x9c\x51\x02\x74\x5a\xaa\x3a\x0c\x46\x9f\xad\x9e\x07\x5a"+        , vecCiphertext = "\x29\x6c\x78\x89\xfd\x99\xf4\x19\x17\xf4\x46\x20"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x8f\x89\x36\xec\x03\x9e\x4e\x4b\xb9\x7e\xbd\x8c\x44\x57\x44\x1f"+        , vecCiphertext = "\xe2\xb0\xc5\xda\x79\xa9\x01\xc1\x74\x5f\x70\x05\x25\xcb\x33\x5b"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xe6\xaf\x6a\x7f\x87\x28\x7d\xa0\x59\xa7\x16\x84\xed\x34\x98\xe1"+        , vecCiphertext = "\x62\x00\x48\xef\x3c\x1e\x73\xe5\x7e\x02\xbb\x85\x62\xc4\x16\xa3\x19\xe7\x3e\x4c\xaa\xc8\xe9\x6a\x1e\xcb\x29\x33\x14\x5a\x1d\x71"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x6a\x8c\xc3\x86\x5f\x76\x89\x7c\x2e\x4b\x24\x5c\xf3\x1c\x51\xf2"+        , vecCiphertext = "\x50\xc8\x30\x3e\xa9\x39\x25\xd6\x40\x90\xd0\x7b\xd1\x09\xdf\xd9\x51\x5a\x5a\x33\x43\x10\x19\xc1\x7d\x93\x46\x59\x99\xa8\xb0\x05\x32\x01\xd7\x23\x12\x0a\x85\x62\xb8\x38\xcd\xff\x25\xbf\x9d\x1e"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xcd\xc4\x6a\xe4\x75\x56\x3d\xe0\x37\x00\x1e\xf8\x4a\xe2\x17\x44"+        , vecCiphertext = "\x2f\x5c\x64\x05\x9d\xb5\x5e\xe0\xfb\x84\x7e\xd5\x13\x00\x37\x46\xac\xa4\xe6\x1c\x71\x1b\x5d\xe2\xe7\xa7\x7f\xfd\x02\xda\x42\xfe\xec\x60\x19\x10\xd3\x46\x7b\xb8\xb3\x6e\xbb\xae\xbc\xe5\xfb\xa3\x0d\x36\xc9\x5f\x48\xa3\xe7\x98\x0f\x0e\x7a\xc2\x99\x33\x2a\x80"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00"+        , vecAAD        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x07\xeb\x1f\x84\xfb\x28\xf8\xcb\x73\xde\x8e\x99\xe2\xf4\x8a\x14"+        , vecCiphertext = "\xa8\xfe\x3e\x87"+        }+    , Vector+        { vecPlaintext  = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00"+        , vecAAD        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x24\xaf\xc9\x80\x5e\x97\x6f\x45\x1e\x6d\x87\xf6\xfe\x10\x65\x14"+        , vecCiphertext = "\x6b\xb0\xfe\xcf\x5d\xed\x9b\x77\xf9\x02\xc7\xd5\xda\x23\x6a\x43\x91\xdd\x02\x97"+        }+    , Vector+        { vecPlaintext  = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00"+        , vecAAD        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xbf\xf9\xb2\xef\x00\xfb\x47\x92\x0c\xc7\x2a\x0c\x0f\x13\xb9\xfd"+        , vecCiphertext = "\x44\xd0\xaa\xf6\xfb\x2f\x1f\x34\xad\xd5\xe8\x06\x4e\x83\xe1\x2a\x2a\xda"+        }+    , Vector+        { vecPlaintext  = ""+        , vecAAD        = ""+        , vecKey        = "\xe6\x60\x21\xd5\xeb\x8e\x4f\x40\x66\xd4\xad\xb9\xc3\x35\x60\xe4"+        , vecNonce      = "\xf4\x6e\x44\xbb\x3d\xa0\x01\x5c\x94\xf7\x08\x87"+        , vecTag        = "\xa4\x19\x4b\x79\x07\x1b\x01\xa8\x7d\x65\xf7\x06\xe3\x94\x95\x78"+        , vecCiphertext = ""+        }+    , Vector+        { vecPlaintext  = "\x7a\x80\x6c"+        , vecAAD        = "\x46\xbb\x91\xc3\xc5"+        , vecKey        = "\x36\x86\x42\x00\xe0\xea\xf5\x28\x4d\x88\x4a\x0e\x77\xd3\x16\x46"+        , vecNonce      = "\xba\xe8\xe3\x7f\xc8\x34\x41\xb1\x60\x34\x56\x6b"+        , vecTag        = "\x71\x1b\xd8\x5b\xc1\xe4\xd3\xe0\xa4\x62\xe0\x74\xee\xa4\x28\xa8"+        , vecCiphertext = "\xaf\x60\xeb"+        }+    , Vector+        { vecPlaintext  = "\xbd\xc6\x6f\x14\x65\x45"+        , vecAAD        = "\xfc\x88\x0c\x94\xa9\x51\x98\x87\x42\x96"+        , vecKey        = "\xae\xdb\x64\xa6\xc5\x90\xbc\x84\xd1\xa5\xe2\x69\xe4\xb4\x78\x01"+        , vecNonce      = "\xaf\xc0\x57\x7e\x34\x69\x9b\x9e\x67\x1f\xdd\x4f"+        , vecTag        = "\xd6\xa9\xc4\x55\x45\xcf\xc1\x1f\x03\xad\x74\x3d\xba\x20\xf9\x66"+        , vecCiphertext = "\xbb\x93\xa3\xe3\x4d\x3c"+        }+    , Vector+        { vecPlaintext  = "\x11\x77\x44\x1f\x19\x54\x95\x86\x0f"+        , vecAAD        = "\x04\x67\x87\xf3\xea\x22\xc1\x27\xaa\xf1\x95\xd1\x89\x47\x28"+        , vecKey        = "\xd5\xcc\x1f\xd1\x61\x32\x0b\x69\x20\xce\x07\x78\x7f\x86\x74\x3b"+        , vecNonce      = "\x27\x5d\x1a\xb3\x2f\x6d\x1f\x04\x34\xd8\x84\x8c"+        , vecTag        = "\x1d\x02\xfd\x0c\xd1\x74\xc8\x4f\xc5\xda\xe2\xf6\x0f\x52\xfd\x2b"+        , vecCiphertext = "\x4f\x37\x28\x1f\x7a\xd1\x29\x49\xd0"+        }+    , Vector+        { vecPlaintext  = "\x9f\x57\x2c\x61\x4b\x47\x45\x91\x44\x74\xe7\xc7"+        , vecAAD        = "\xc9\x88\x2e\x53\x86\xfd\x9f\x92\xec\x48\x9c\x8f\xde\x2b\xe2\xcf\x97\xe7\x4e\x93"+        , vecKey        = "\xb3\xfe\xd1\x47\x3c\x52\x8b\x84\x26\xa5\x82\x99\x59\x29\xa1\x49"+        , vecNonce      = "\x9e\x9a\xd8\x78\x0c\x8d\x63\xd0\xab\x41\x49\xc0"+        , vecTag        = "\xc1\xdc\x2f\x87\x1f\xb7\x56\x1d\xa1\x28\x6e\x65\x5e\x24\xb7\xb0"+        , vecCiphertext = "\xf5\x46\x73\xc5\xdd\xf7\x10\xc7\x45\x64\x1c\x8b"+        }+    , Vector+        { vecPlaintext  = "\x0d\x8c\x84\x51\x17\x80\x82\x35\x5c\x9e\x94\x0f\xea\x2f\x58"+        , vecAAD        = "\x29\x50\xa7\x0d\x5a\x1d\xb2\x31\x6f\xd5\x68\x37\x8d\xa1\x07\xb5\x2b\x0d\xa5\x52\x10\xcc\x1c\x1b\x0a"+        , vecKey        = "\x2d\x4e\xd8\x7d\xa4\x41\x02\x95\x2e\xf9\x4b\x02\xb8\x05\x24\x9b"+        , vecNonce      = "\xac\x80\xe6\xf6\x14\x55\xbf\xac\x83\x08\xa2\xd4"+        , vecTag        = "\x83\xb3\x44\x9b\x9f\x39\x55\x2d\xe9\x9d\xc2\x14\xa1\x19\x0b\x0b"+        , vecCiphertext = "\xc9\xff\x54\x5e\x07\xb8\x8a\x01\x5f\x05\xb2\x74\x54\x0a\xa1"+        }+    , Vector+        { vecPlaintext  = "\x6b\x3d\xb4\xda\x3d\x57\xaa\x94\x84\x2b\x98\x03\xa9\x6e\x07\xfb\x6d\xe7"+        , vecAAD        = "\x18\x60\xf7\x62\xeb\xfb\xd0\x82\x84\xe4\x21\x70\x2d\xe0\xde\x18\xba\xa9\xc9\x59\x62\x91\xb0\x84\x66\xf3\x7d\xe2\x1c\x7f"+        , vecKey        = "\xbd\xe3\xb2\xf2\x04\xd1\xe9\xf8\xb0\x6b\xc4\x7f\x97\x45\xb3\xd1"+        , vecNonce      = "\xae\x06\x55\x6f\xb6\xaa\x78\x90\xbe\xbc\x18\xfe"+        , vecTag        = "\x3e\x37\x70\x94\xf0\x47\x09\xf6\x4d\x7b\x98\x53\x10\xa4\xdb\x84"+        , vecCiphertext = "\x62\x98\xb2\x96\xe2\x4e\x8c\xc3\x5d\xce\x0b\xed\x48\x4b\x7f\x30\xd5\x80"+        }+    , Vector+        { vecPlaintext  = "\xe4\x2a\x3c\x02\xc2\x5b\x64\x86\x9e\x14\x6d\x7b\x23\x39\x87\xbd\xdf\xc2\x40\x87\x1d"+        , vecAAD        = "\x75\x76\xf7\x02\x8e\xc6\xeb\x5e\xa7\xe2\x98\x34\x2a\x94\xd4\xb2\x02\xb3\x70\xef\x97\x68\xec\x65\x61\xc4\xfe\x6b\x7e\x72\x96\xfa\x85\x9c\x21"+        , vecKey        = "\xf9\x01\xcf\xe8\xa6\x96\x15\xa9\x3f\xdf\x7a\x98\xca\xd4\x81\x79"+        , vecNonce      = "\x62\x45\x70\x9f\xb1\x88\x53\xf6\x8d\x83\x36\x40"+        , vecTag        = "\x2d\x15\x50\x6c\x84\xa9\xed\xd6\x5e\x13\xe9\xd2\x4a\x2a\x6e\x70"+        , vecCiphertext = "\x39\x1c\xc3\x28\xd4\x84\xa4\xf4\x64\x06\x18\x1b\xcd\x62\xef\xd9\xb3\xee\x19\x7d\x05"+        }+    ]++vectors256 :: [Vector AES256]+vectors256 =+    [ Vector+        { vecPlaintext  = ""+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x07\xf5\xf4\x16\x9b\xbf\x55\xa8\x40\x0c\xd4\x7e\xa6\xfd\x40\x0f"+        , vecCiphertext = ""+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x84\x31\x22\x13\x0f\x73\x64\xb7\x61\xe0\xb9\x74\x27\xe3\xdf\x28"+        , vecCiphertext = "\xc2\xef\x32\x8e\x5c\x71\xc8\x3b"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x8c\xa5\x0d\xa9\xae\x65\x59\xe4\x8f\xd1\x0f\x6e\x5c\x9c\xa1\x7e"+        , vecCiphertext = "\x9a\xab\x2a\xeb\x3f\xaa\x0a\x34\xae\xa8\xe2\xb1"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xc9\xea\xc6\xfa\x70\x09\x42\x70\x2e\x90\x86\x23\x83\xc6\xc3\x66"+        , vecCiphertext = "\x85\xa0\x1b\x63\x02\x5b\xa1\x9b\x7f\xd3\xdd\xfc\x03\x3b\x3e\x76"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xe8\x19\xe6\x3a\xbc\xd0\x20\xb0\x06\xa9\x76\x39\x76\x32\xeb\x5d"+        , vecCiphertext = "\x4a\x6a\x9d\xb4\xc8\xc6\x54\x92\x01\xb9\xed\xb5\x30\x06\xcb\xa8\x21\xec\x9c\xf8\x50\x94\x8a\x7c\x86\xc6\x8a\xc7\x53\x9d\x02\x7f"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x79\x0b\xc9\x68\x80\xa9\x9b\xa8\x04\xbd\x12\xc0\xe6\xa2\x2c\xc4"+        , vecCiphertext = "\xc0\x0d\x12\x18\x93\xa9\xfa\x60\x3f\x48\xcc\xc1\xca\x3c\x57\xce\x74\x99\x24\x5e\xa0\x04\x6d\xb1\x6c\x53\xc7\xc6\x6f\xe7\x17\xe3\x9c\xf6\xc7\x48\x83\x7b\x61\xf6\xee\x3a\xdc\xee\x17\x53\x4e\xd5"+        }+    , Vector+        { vecPlaintext  = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x11\x28\x64\xc2\x69\xfc\x0d\x9d\x88\xc6\x1f\xa4\x7e\x39\xaa\x08"+        , vecCiphertext = "\xc2\xd5\x16\x0a\x1f\x86\x83\x83\x49\x10\xac\xda\xfc\x41\xfb\xb1\x63\x2d\x4a\x35\x3e\x8b\x90\x5e\xc9\xa5\x49\x9a\xc3\x4f\x96\xc7\xe1\x04\x9e\xb0\x80\x88\x38\x91\xa4\xdb\x8c\xaa\xa1\xf9\x9d\xd0\x04\xd8\x04\x87\x54\x07\x35\x23\x4e\x37\x44\x51\x2c\x6f\x90\xce"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x91\x21\x3f\x26\x7e\x3b\x45\x2f\x02\xd0\x1a\xe3\x3e\x4e\xc8\x54"+        , vecCiphertext = "\x1d\xe2\x29\x67\x23\x7a\x81\x32"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xc1\xa4\xa1\x9a\xe8\x00\x94\x1c\xcd\xc5\x7c\xc8\x41\x3c\x27\x7f"+        , vecCiphertext = "\x16\x3d\x6f\x9c\xc1\xb3\x46\xcd\x45\x3a\x2e\x4c"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xb2\x92\xd2\x8f\xf6\x11\x89\xe8\xe4\x9f\x38\x75\xef\x91\xaf\xf7"+        , vecCiphertext = "\xc9\x15\x45\x82\x3c\xc2\x4f\x17\xdb\xb0\xe9\xe8\x07\xd5\xec\x17"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xae\xa1\xba\xd1\x27\x02\xe1\x96\x56\x04\x37\x4a\xab\x96\xdb\xbc"+        , vecCiphertext = "\x07\xda\xd3\x64\xbf\xc2\xb9\xda\x89\x11\x6d\x7b\xef\x6d\xaa\xaf\x6f\x25\x55\x10\xaa\x65\x4f\x92\x0a\xc8\x1b\x94\xe8\xba\xd3\x65"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x03\x33\x27\x42\xb2\x28\xc6\x47\x17\x36\x16\xcf\xd4\x4c\x54\xeb"+        , vecCiphertext = "\xc6\x7a\x1f\x0f\x56\x7a\x51\x98\xaa\x1f\xcc\x8e\x3f\x21\x31\x43\x36\xf7\xf5\x1c\xa8\xb1\xaf\x61\xfe\xac\x35\xa8\x64\x16\xfa\x47\xfb\xca\x3b\x5f\x74\x9c\xdf\x56\x45\x27\xf2\x31\x4f\x42\xfe\x25"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = "\x01"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x5b\xde\x02\x85\x03\x7c\x5d\xe8\x1e\x5b\x57\x0a\x04\x9b\x62\xa0"+        , vecCiphertext = "\x67\xfd\x45\xe1\x26\xbf\xb9\xa7\x99\x30\xc4\x3a\xad\x2d\x36\x96\x7d\x3f\x0e\x4d\x21\x7c\x1e\x55\x1f\x59\x72\x78\x70\xbe\xef\xc9\x8c\xb9\x33\xa8\xfc\xe9\xde\x88\x7b\x1e\x40\x79\x99\x88\xdb\x1f\xc3\xf9\x18\x80\xed\x40\x5b\x2d\xd2\x98\x31\x88\x58\x46\x7c\x89"+        }+    , Vector+        { vecPlaintext  = "\x02\x00\x00\x00"+        , vecAAD        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\x18\x35\xe5\x17\x74\x1d\xfd\xdc\xcf\xa0\x7f\xa4\x66\x1b\x74\xcf"+        , vecCiphertext = "\x22\xb3\xf4\xcd"+        }+    , Vector+        { vecPlaintext  = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00"+        , vecAAD        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xb8\x79\xad\x97\x6d\x82\x42\xac\xc1\x88\xab\x59\xca\xbf\xe3\x07"+        , vecCiphertext = "\x43\xdd\x01\x63\xcd\xb4\x8f\x9f\xe3\x21\x2b\xf6\x1b\x20\x19\x76\x06\x7f\x34\x2b"+        }+    , Vector+        { vecPlaintext  = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00"+        , vecAAD        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00"+        , vecKey        = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xcf\xcd\xf5\x04\x21\x12\xaa\x29\x68\x5c\x91\x2f\xc2\x05\x65\x43"+        , vecCiphertext = "\x46\x24\x01\x72\x4b\x5c\xe6\x58\x8d\x5a\x54\xaa\xe5\x37\x55\x13\xa0\x75"+        }+    , Vector+        { vecPlaintext  = ""+        , vecAAD        = ""+        , vecKey        = "\xe6\x60\x21\xd5\xeb\x8e\x4f\x40\x66\xd4\xad\xb9\xc3\x35\x60\xe4\xf4\x6e\x44\xbb\x3d\xa0\x01\x5c\x94\xf7\x08\x87\x36\x86\x42\x00"+        , vecNonce      = "\xe0\xea\xf5\x28\x4d\x88\x4a\x0e\x77\xd3\x16\x46"+        , vecTag        = "\x16\x9f\xbb\x2f\xbf\x38\x9a\x99\x5f\x63\x90\xaf\x22\x22\x8a\x62"+        , vecCiphertext = ""+        }+    , Vector+        { vecPlaintext  = "\x67\x1f\xdd"+        , vecAAD        = "\x4f\xbd\xc6\x6f\x14"+        , vecKey        = "\xba\xe8\xe3\x7f\xc8\x34\x41\xb1\x60\x34\x56\x6b\x7a\x80\x6c\x46\xbb\x91\xc3\xc5\xae\xdb\x64\xa6\xc5\x90\xbc\x84\xd1\xa5\xe2\x69"+        , vecNonce      = "\xe4\xb4\x78\x01\xaf\xc0\x57\x7e\x34\x69\x9b\x9e"+        , vecTag        = "\x93\xda\x9b\xb8\x13\x33\xae\xe0\xc7\x85\xb2\x40\xd3\x19\x71\x9d"+        , vecCiphertext = "\x0e\xac\xcb"+        }+    , Vector+        { vecPlaintext  = "\x19\x54\x95\x86\x0f\x04"+        , vecAAD        = "\x67\x87\xf3\xea\x22\xc1\x27\xaa\xf1\x95"+        , vecKey        = "\x65\x45\xfc\x88\x0c\x94\xa9\x51\x98\x87\x42\x96\xd5\xcc\x1f\xd1\x61\x32\x0b\x69\x20\xce\x07\x78\x7f\x86\x74\x3b\x27\x5d\x1a\xb3"+        , vecNonce      = "\x2f\x6d\x1f\x04\x34\xd8\x84\x8c\x11\x77\x44\x1f"+        , vecTag        = "\x6b\x62\xb8\x4d\xc4\x0c\x84\x63\x6a\x5e\xc1\x20\x20\xec\x8c\x2c"+        , vecCiphertext = "\xa2\x54\xda\xd4\xf3\xf9"+        }+    , Vector+        { vecPlaintext  = "\xc9\x88\x2e\x53\x86\xfd\x9f\x92\xec"+        , vecAAD        = "\x48\x9c\x8f\xde\x2b\xe2\xcf\x97\xe7\x4e\x93\x2d\x4e\xd8\x7d"+        , vecKey        = "\xd1\x89\x47\x28\xb3\xfe\xd1\x47\x3c\x52\x8b\x84\x26\xa5\x82\x99\x59\x29\xa1\x49\x9e\x9a\xd8\x78\x0c\x8d\x63\xd0\xab\x41\x49\xc0"+        , vecNonce      = "\x9f\x57\x2c\x61\x4b\x47\x45\x91\x44\x74\xe7\xc7"+        , vecTag        = "\xc0\xfd\x3d\xc6\x62\x8d\xfe\x55\xeb\xb0\xb9\xfb\x22\x95\xc8\xc2"+        , vecCiphertext = "\x0d\xf9\xe3\x08\x67\x82\x44\xc4\x4b"+        }+    , Vector+        { vecPlaintext  = "\x1d\xb2\x31\x6f\xd5\x68\x37\x8d\xa1\x07\xb5\x2b"+        , vecAAD        = "\x0d\xa5\x52\x10\xcc\x1c\x1b\x0a\xbd\xe3\xb2\xf2\x04\xd1\xe9\xf8\xb0\x6b\xc4\x7f"+        , vecKey        = "\xa4\x41\x02\x95\x2e\xf9\x4b\x02\xb8\x05\x24\x9b\xac\x80\xe6\xf6\x14\x55\xbf\xac\x83\x08\xa2\xd4\x0d\x8c\x84\x51\x17\x80\x82\x35"+        , vecNonce      = "\x5c\x9e\x94\x0f\xea\x2f\x58\x29\x50\xa7\x0d\x5a"+        , vecTag        = "\x40\x40\x99\xc2\x58\x7f\x64\x97\x9f\x21\x82\x67\x06\xd4\x97\xd5"+        , vecCiphertext = "\x8d\xbe\xb9\xf7\x25\x5b\xf5\x76\x9d\xd5\x66\x92"+        }+    , Vector+        { vecPlaintext  = "\x21\x70\x2d\xe0\xde\x18\xba\xa9\xc9\x59\x62\x91\xb0\x84\x66"+        , vecAAD        = "\xf3\x7d\xe2\x1c\x7f\xf9\x01\xcf\xe8\xa6\x96\x15\xa9\x3f\xdf\x7a\x98\xca\xd4\x81\x79\x62\x45\x70\x9f"+        , vecKey        = "\x97\x45\xb3\xd1\xae\x06\x55\x6f\xb6\xaa\x78\x90\xbe\xbc\x18\xfe\x6b\x3d\xb4\xda\x3d\x57\xaa\x94\x84\x2b\x98\x03\xa9\x6e\x07\xfb"+        , vecNonce      = "\x6d\xe7\x18\x60\xf7\x62\xeb\xfb\xd0\x82\x84\xe4"+        , vecTag        = "\xb3\x08\x0d\x28\xf6\xeb\xb5\xd3\x64\x8c\xe9\x7b\xd5\xba\x67\xfd"+        , vecCiphertext = "\x79\x35\x76\xdf\xa5\xc0\xf8\x87\x29\xa7\xed\x3c\x2f\x1b\xff"+        }+    , Vector+        { vecPlaintext  = "\xb2\x02\xb3\x70\xef\x97\x68\xec\x65\x61\xc4\xfe\x6b\x7e\x72\x96\xfa\x85"+        , vecAAD        = "\x9c\x21\x59\x05\x8b\x1f\x0f\xe9\x14\x33\xa5\xbd\xc2\x0e\x21\x4e\xab\x7f\xec\xef\x44\x54\xa1\x0e\xf0\x65\x7d\xf2\x1a\xc7"+        , vecKey        = "\xb1\x88\x53\xf6\x8d\x83\x36\x40\xe4\x2a\x3c\x02\xc2\x5b\x64\x86\x9e\x14\x6d\x7b\x23\x39\x87\xbd\xdf\xc2\x40\x87\x1d\x75\x76\xf7"+        , vecNonce      = "\x02\x8e\xc6\xeb\x5e\xa7\xe2\x98\x34\x2a\x94\xd4"+        , vecTag        = "\x45\x4f\xc2\xa1\x54\xfe\xa9\x1f\x83\x63\xa3\x9f\xec\x7d\x0a\x49"+        , vecCiphertext = "\x85\x7e\x16\xa6\x49\x15\xa7\x87\x63\x76\x87\xdb\x4a\x95\x19\x63\x5c\xdd"+        }+    , Vector+        { vecPlaintext  = "\xce\xd5\x32\xce\x41\x59\xb0\x35\x27\x7d\x4d\xfb\xb7\xdb\x62\x96\x8b\x13\xcd\x4e\xec"+        , vecAAD        = "\x73\x43\x20\xcc\xc9\xd9\xbb\xbb\x19\xcb\x81\xb2\xaf\x4e\xcb\xc3\xe7\x28\x34\x32\x1f\x7a\xa0\xf7\x0b\x72\x82\xb4\xf3\x3d\xf2\x3f\x16\x75\x41"+        , vecKey        = "\x3c\x53\x5d\xe1\x92\xea\xed\x38\x22\xa2\xfb\xbe\x2c\xa9\xdf\xc8\x82\x55\xe1\x4a\x66\x1b\x8a\xa8\x2c\xc5\x42\x36\x09\x3b\xbc\x23"+        , vecNonce      = "\x68\x80\x89\xe5\x55\x40\xdb\x18\x72\x50\x4e\x1c"+        , vecTag        = "\x9d\x6c\x70\x29\x67\x5b\x89\xea\xf4\xba\x1d\xed\x1a\x28\x65\x94"+        , vecCiphertext = "\x62\x66\x60\xc2\x6e\xa6\x61\x2f\xb1\x7a\xd9\x1e\x8e\x76\x76\x39\xed\xd6\xc9\xfa\xee"+        }+    ]++vectorsWrap256 :: [Vector AES256]+vectorsWrap256 =+    [ Vector+        { vecPlaintext  = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x4d\xb9\x23\xdc\x79\x3e\xe6\x49\x7c\x76\xdc\xc0\x3a\x98\xe1\x08"+        , vecAAD        = ""+        , vecKey        = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecCiphertext = "\xf3\xf8\x0f\x2c\xf0\xcb\x2d\xd9\xc5\x98\x4f\xcd\xa9\x08\x45\x6c\xc5\x37\x70\x3b\x5b\xa7\x03\x24\xa6\x79\x3a\x7b\xf2\x18\xd3\xea"+        }+    , Vector+        { vecPlaintext  = "\xeb\x36\x40\x27\x7c\x7f\xfd\x13\x03\xc7\xa5\x42\xd0\x2d\x3e\x4c\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecAAD        = ""+        , vecKey        = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecNonce      = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecTag        = "\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+        , vecCiphertext = "\x18\xce\x4f\x0b\x8c\xb4\xd0\xca\xc6\x5f\xea\x8f\x79\x25\x7b\x20\x88\x8e\x53\xe7\x22\x99\xe5\x6d"+        }+    ]++makeEncryptionTest :: BlockCipher128 aes => Int -> Vector aes -> TestTree+makeEncryptionTest i vec@Vector{..} =+    testCase (show i) $+        (t, vecCiphertext) @=? encrypt (vecCipher vec) n vecAAD vecPlaintext+  where t = AuthTag (B.convert vecTag)+        n = throwCryptoError (nonce vecNonce)++makeDecryptionTest :: BlockCipher128 aes => Int -> Vector aes -> TestTree+makeDecryptionTest i vec@Vector{..} =+    testCase (show i) $+        Just vecPlaintext @=? decrypt (vecCipher vec) n vecAAD vecCiphertext t+  where t = AuthTag (B.convert vecTag)+        n = throwCryptoError (nonce vecNonce)++katTests :: TestName+         -> (forall c . BlockCipher128 c => Int -> Vector c -> TestTree)+         -> TestTree+katTests name makeTest = testGroup name+    [ testGroup "AES128" $ zipWith makeTest [1..] vectors128+    , testGroup "AES256" $ zipWith makeTest [1..] vectors256+    , testGroup "CounterWrap" $ zipWith makeTest [1..] vectorsWrap256+    ]++newtype Key c = Key ByteString+    deriving (Show,Eq)++instance Arbitrary (Key AES128) where+    arbitrary = Key <$> arbitraryBS 16++instance Arbitrary (Key AES256) where+    arbitrary = Key <$> arbitraryBS 32++instance Arbitrary Nonce where+    arbitrary = throwCryptoError . nonce <$> arbitraryBS 12++encDecTest :: BlockCipher128 c+           => Proxy c -> Key c -> Nonce+           -> ArbitraryBS0_2901 -> ArbitraryBS0_2901 -> Property+encDecTest prx (Key key) iv (ArbitraryBS0_2901 aad) (ArbitraryBS0_2901 input) =+    let c = throwCryptoError (cipherInit key) `asProxyTypeOf` prx+        (tag, ciphertext) = encrypt c iv aad input+     in decrypt c iv aad ciphertext tag === Just input++tests :: TestTree+tests = testGroup "AES-GCM-SIV"+    [ testGroup "KATs"+        [ katTests "encrypt" makeEncryptionTest+        , katTests "decrypt" makeDecryptionTest+        ]+    , testGroup "properties"+        [ testProperty "AES128" $ encDecTest (Proxy :: Proxy AES128)+        , testProperty "AES256" $ encDecTest (Proxy :: Proxy AES256)+        ]+    ]
tests/KAT_AFIS.hs view
@@ -23,8 +23,8 @@       )     ] -mergeKATs = map toProp $ zip mergeVec [(0 :: Int)..]-  where toProp ((nbExpands, hashAlg, expected, dat), i) =+mergeKATs = zipWith toProp mergeVec [(0 :: Int)..]+  where toProp (nbExpands, hashAlg, expected, dat) i =             testCase ("merge " ++ show i) (expected @=? AFIS.merge hashAlg nbExpands dat)  data AFISParams = AFISParams B.ByteString Int SHA1 ChaChaDRG
tests/KAT_Argon2.hs view
@@ -28,9 +28,9 @@     ]  kdfTests :: [TestTree]-kdfTests = map toKDFTest $ zip is vectors+kdfTests = zipWith toKDFTest is vectors   where-    toKDFTest (i, v) =+    toKDFTest i v =         testCase (show i)             (CryptoPassed (kdfResult v) @=? Argon2.hash (kdfOptions v) (kdfPass v) (kdfSalt v) (B.length $ kdfResult v)) 
tests/KAT_Ed25519.hs view
@@ -47,18 +47,18 @@     ]  -doPublicKeyTest (i, vec) = testCase (show i) (pub @=? Ed25519.toPublic sec)+doPublicKeyTest i vec = testCase (show i) (pub @=? Ed25519.toPublic sec)   where         !pub = throwCryptoError $ Ed25519.publicKey (vecPub vec)         !sec = throwCryptoError $ Ed25519.secretKey (vecSec vec) -doSignatureTest (i, vec) = testCase (show i) (sig @=? Ed25519.sign sec pub (vecMsg vec))+doSignatureTest i vec = testCase (show i) (sig @=? Ed25519.sign sec pub (vecMsg vec))   where         !sig = throwCryptoError $ Ed25519.signature (vecSig vec)         !pub = throwCryptoError $ Ed25519.publicKey (vecPub vec)         !sec = throwCryptoError $ Ed25519.secretKey (vecSec vec) -doVerifyTest (i, vec) = testCase (show i) (True @=? Ed25519.verify pub (vecMsg vec) sig)+doVerifyTest i vec = testCase (show i) (True @=? Ed25519.verify pub (vecMsg vec) sig)   where         !sig = throwCryptoError $ Ed25519.signature (vecSig vec)         !pub = throwCryptoError $ Ed25519.publicKey (vecPub vec)@@ -66,7 +66,7 @@  tests = testGroup "Ed25519"     [ testCase  "gen secretkey" (Ed25519.generateSecretKey *> pure ())-    , testGroup "gen publickey" $ map doPublicKeyTest (zip [katZero..] vectors)-    , testGroup "gen signature" $ map doSignatureTest (zip [katZero..] vectors)-    , testGroup "verify sig" $ map doVerifyTest (zip [katZero..] vectors)+    , testGroup "gen publickey" $ zipWith doPublicKeyTest [katZero..] vectors+    , testGroup "gen signature" $ zipWith doSignatureTest [katZero..] vectors+    , testGroup "verify sig" $ zipWith doVerifyTest [katZero..] vectors     ]
tests/KAT_Ed448.hs view
@@ -65,18 +65,18 @@     ]  -doPublicKeyTest (i, vec) = testCase (show i) (pub @=? Ed448.toPublic sec)+doPublicKeyTest i vec = testCase (show i) (pub @=? Ed448.toPublic sec)   where         !pub = throwCryptoError $ Ed448.publicKey (vecPub vec)         !sec = throwCryptoError $ Ed448.secretKey (vecSec vec) -doSignatureTest (i, vec) = testCase (show i) (sig @=? Ed448.sign sec pub (vecMsg vec))+doSignatureTest i vec = testCase (show i) (sig @=? Ed448.sign sec pub (vecMsg vec))   where         !sig = throwCryptoError $ Ed448.signature (vecSig vec)         !pub = throwCryptoError $ Ed448.publicKey (vecPub vec)         !sec = throwCryptoError $ Ed448.secretKey (vecSec vec) -doVerifyTest (i, vec) = testCase (show i) (True @=? Ed448.verify pub (vecMsg vec) sig)+doVerifyTest i vec = testCase (show i) (True @=? Ed448.verify pub (vecMsg vec) sig)   where         !sig = throwCryptoError $ Ed448.signature (vecSig vec)         !pub = throwCryptoError $ Ed448.publicKey (vecPub vec)@@ -84,7 +84,7 @@  tests = testGroup "Ed448"     [ testCase  "gen secretkey" (Ed448.generateSecretKey *> pure ())-    , testGroup "gen publickey" $ map doPublicKeyTest (zip [katZero..] vectors)-    , testGroup "gen signature" $ map doSignatureTest (zip [katZero..] vectors)-    , testGroup "verify sig" $ map doVerifyTest (zip [katZero..] vectors)+    , testGroup "gen publickey" $ zipWith doPublicKeyTest [katZero..] vectors+    , testGroup "gen signature" $ zipWith doSignatureTest [katZero..] vectors+    , testGroup "verify sig" $ zipWith doVerifyTest [katZero..] vectors     ]
tests/KAT_PBKDF2.hs view
@@ -67,21 +67,21 @@     , testGroup "KATs-HMAC-SHA512" (katTests (PBKDF2.prfHMAC SHA512) vectors_hmac_sha512)     , testGroup "KATs-HMAC-SHA512 (fast)" (katTestFastPBKDF2_SHA512 vectors_hmac_sha512)     ]-  where katTests prf vects = map (toKatTest prf) $ zip is vects+  where katTests prf = zipWith (toKatTest prf) is -        toKatTest prf (i, ((pass, salt, iter, dkLen), output)) =+        toKatTest prf i ((pass, salt, iter, dkLen), output) =             testCase (show i) (output @=? PBKDF2.generate prf (PBKDF2.Parameters iter dkLen) pass salt) -        katTestFastPBKDF2_SHA1 = map toKatTestFastPBKDF2_SHA1 . zip is-        toKatTestFastPBKDF2_SHA1 (i, ((pass, salt, iter, dkLen), output)) =+        katTestFastPBKDF2_SHA1 = zipWith toKatTestFastPBKDF2_SHA1 is+        toKatTestFastPBKDF2_SHA1 i ((pass, salt, iter, dkLen), output) =             testCase (show i) (output @=? PBKDF2.fastPBKDF2_SHA1 (PBKDF2.Parameters iter dkLen) pass salt) -        katTestFastPBKDF2_SHA256 = map toKatTestFastPBKDF2_SHA256 . zip is-        toKatTestFastPBKDF2_SHA256 (i, ((pass, salt, iter, dkLen), output)) =+        katTestFastPBKDF2_SHA256 = zipWith toKatTestFastPBKDF2_SHA256 is+        toKatTestFastPBKDF2_SHA256 i ((pass, salt, iter, dkLen), output) =             testCase (show i) (output @=? PBKDF2.fastPBKDF2_SHA256 (PBKDF2.Parameters iter dkLen) pass salt) -        katTestFastPBKDF2_SHA512 = map toKatTestFastPBKDF2_SHA512 . zip is-        toKatTestFastPBKDF2_SHA512 (i, ((pass, salt, iter, dkLen), output)) =+        katTestFastPBKDF2_SHA512 = zipWith toKatTestFastPBKDF2_SHA512 is+        toKatTestFastPBKDF2_SHA512 i ((pass, salt, iter, dkLen), output) =             testCase (show i) (output @=? PBKDF2.fastPBKDF2_SHA512 (PBKDF2.Parameters iter dkLen) pass salt)  
tests/KAT_PubKey.hs view
@@ -25,7 +25,7 @@                            , dbMask :: ByteString                            } -doMGFTest (i, vmgf) = testCase (show i) (dbMask vmgf @=? actual)+doMGFTest i vmgf = testCase (show i) (dbMask vmgf @=? actual)     where actual = mgf1 SHA1 (seed vmgf) (B.length $ dbMask vmgf)  vectorsMGF =@@ -36,7 +36,7 @@     ]  tests = testGroup "PubKey"-    [ testGroup "MGF1" $ map doMGFTest (zip [katZero..] vectorsMGF)+    [ testGroup "MGF1" $ zipWith doMGFTest [katZero..] vectorsMGF     , rsaTests     , pssTests     , oaepTests
tests/KAT_PubKey/DSA.hs view
@@ -331,32 +331,32 @@     , DSA.public_params = pgq vector     } -doSignatureTest hashAlg (i, vector) = testCase (show i) (expected @=? actual)+doSignatureTest hashAlg i vector = testCase (show i) (expected @=? actual)     where expected = Just $ DSA.Signature (r vector) (s vector)           actual   = DSA.signWith (k vector) (vectorToPrivate vector) hashAlg (msg vector) -doVerifyTest hashAlg (i, vector) = testCase (show i) (True @=? actual)+doVerifyTest hashAlg i vector = testCase (show i) (True @=? actual)     where actual = DSA.verify hashAlg (vectorToPublic vector) (DSA.Signature (r vector) (s vector)) (msg vector)  dsaTests = testGroup "DSA"     [ testGroup "SHA1"-        [ testGroup "signature" $ map (doSignatureTest SHA1) (zip [katZero..] vectorsSHA1)-        , testGroup "verify" $ map (doVerifyTest SHA1) (zip [katZero..] vectorsSHA1)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA1) [katZero..] vectorsSHA1+        , testGroup "verify" $ zipWith (doVerifyTest SHA1) [katZero..] vectorsSHA1         ]     , testGroup "SHA224"-        [ testGroup "signature" $ map (doSignatureTest SHA224) (zip [katZero..] vectorsSHA224)-        , testGroup "verify" $ map (doVerifyTest SHA224) (zip [katZero..] vectorsSHA224)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA224) [katZero..] vectorsSHA224+        , testGroup "verify" $ zipWith (doVerifyTest SHA224) [katZero..] vectorsSHA224         ]     , testGroup "SHA256"-        [ testGroup "signature" $ map (doSignatureTest SHA256) (zip [katZero..] vectorsSHA256)-        , testGroup "verify" $ map (doVerifyTest SHA256) (zip [katZero..] vectorsSHA256)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA256) [katZero..] vectorsSHA256+        , testGroup "verify" $ zipWith (doVerifyTest SHA256) [katZero..] vectorsSHA256         ]     , testGroup "SHA384"-        [ testGroup "signature" $ map (doSignatureTest SHA384) (zip [katZero..] vectorsSHA384)-        , testGroup "verify" $ map (doVerifyTest SHA384) (zip [katZero..] vectorsSHA384)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA384) [katZero..] vectorsSHA384+        , testGroup "verify" $ zipWith (doVerifyTest SHA384) [katZero..] vectorsSHA384         ]     , testGroup "SHA512"-        [ testGroup "signature" $ map (doSignatureTest SHA512) (zip [katZero..] vectorsSHA512)-        , testGroup "verify" $ map (doVerifyTest SHA512) (zip [katZero..] vectorsSHA512)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA512) [katZero..] vectorsSHA512+        , testGroup "verify" $ zipWith (doVerifyTest SHA512) [katZero..] vectorsSHA512         ]     ]
tests/KAT_PubKey/ECC.hs view
@@ -136,7 +136,7 @@         }     ] -doPointValidTest (i, vector) = testCase (show i) (valid vector @=? ECC.isPointValid (curve vector) (ECC.Point (x vector) (y vector)))+doPointValidTest i vector = testCase (show i) (valid vector @=? ECC.isPointValid (curve vector) (ECC.Point (x vector) (y vector)))  arbitraryPoint :: ECC.Curve -> Gen ECC.Point arbitraryPoint aCurve =@@ -146,7 +146,7 @@     pointGen = ECC.pointBaseMul aCurve <$> choose (1, n - 1)  eccTests = testGroup "ECC"-    [ testGroup "valid-point" $ map doPointValidTest (zip [katZero..] vectorsPoint)+    [ testGroup "valid-point" $ zipWith doPointValidTest [katZero..] vectorsPoint     , localOption (QuickCheckTests 20) $ testGroup "property"         [ testProperty "point-add" $ \aCurve (QAInteger r1) (QAInteger r2) ->             let curveN   = ECC.ecc_n . ECC.common_curve $ aCurve
tests/KAT_PubKey/ECDSA.hs view
@@ -490,32 +490,32 @@ vectorToPublic :: VectorECDSA -> ECDSA.PublicKey vectorToPublic vector = ECDSA.PublicKey (curve vector) (q vector) -doSignatureTest hashAlg (i, vector) = testCase (show i) (expected @=? actual)+doSignatureTest hashAlg i vector = testCase (show i) (expected @=? actual)   where expected = Just $ ECDSA.Signature (r vector) (s vector)         actual   = ECDSA.signWith (k vector) (vectorToPrivate vector) hashAlg (msg vector) -doVerifyTest hashAlg (i, vector) = testCase (show i) (True @=? actual)+doVerifyTest hashAlg i vector = testCase (show i) (True @=? actual)   where actual = ECDSA.verify hashAlg (vectorToPublic vector) (ECDSA.Signature (r vector) (s vector)) (msg vector)  ecdsaTests = testGroup "ECDSA"     [ testGroup "SHA1"-        [ testGroup "signature" $ map (doSignatureTest SHA1) (zip [katZero..] vectorsSHA1)-        , testGroup "verify" $ map (doVerifyTest SHA1) (zip [katZero..] vectorsSHA1)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA1) [katZero..] vectorsSHA1+        , testGroup "verify" $ zipWith (doVerifyTest SHA1) [katZero..] vectorsSHA1         ]     , testGroup "SHA224"-        [ testGroup "signature" $ map (doSignatureTest SHA224) (zip [katZero..] rfc6979_vectorsSHA224)-        , testGroup "verify" $ map (doVerifyTest SHA224) (zip [katZero..] rfc6979_vectorsSHA224)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA224) [katZero..] rfc6979_vectorsSHA224+        , testGroup "verify" $ zipWith (doVerifyTest SHA224) [katZero..] rfc6979_vectorsSHA224         ]     , testGroup "SHA256"-        [ testGroup "signature" $ map (doSignatureTest SHA256) (zip [katZero..] rfc6979_vectorsSHA256)-        , testGroup "verify" $ map (doVerifyTest SHA256) (zip [katZero..] rfc6979_vectorsSHA256)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA256) [katZero..] rfc6979_vectorsSHA256+        , testGroup "verify" $ zipWith (doVerifyTest SHA256) [katZero..] rfc6979_vectorsSHA256         ]     , testGroup "SHA384"-        [ testGroup "signature" $ map (doSignatureTest SHA384) (zip [katZero..] rfc6979_vectorsSHA384)-        , testGroup "verify" $ map (doVerifyTest SHA384) (zip [katZero..] rfc6979_vectorsSHA384)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA384) [katZero..] rfc6979_vectorsSHA384+        , testGroup "verify" $ zipWith (doVerifyTest SHA384) [katZero..] rfc6979_vectorsSHA384         ]     , testGroup "SHA512"-        [ testGroup "signature" $ map (doSignatureTest SHA512) (zip [katZero..] rfc6979_vectorsSHA512)-        , testGroup "verify" $ map (doVerifyTest SHA512) (zip [katZero..] rfc6979_vectorsSHA512)+        [ testGroup "signature" $ zipWith (doSignatureTest SHA512) [katZero..] rfc6979_vectorsSHA512+        , testGroup "verify" $ zipWith (doVerifyTest SHA512) [katZero..] rfc6979_vectorsSHA512         ]     ]
tests/KAT_PubKey/OAEP.hs view
@@ -81,17 +81,17 @@         }     ] -doEncryptionTest key (i, vec) = testCase (show i) (Right (cipherText vec) @=? actual)-    where actual = OAEP.encryptWithSeed (seed vec) (OAEP.defaultOAEPParams SHA1) key (message vec) +doEncryptionTest key i vec = testCase (show i) (Right (cipherText vec) @=? actual)+    where actual = OAEP.encryptWithSeed (seed vec) (OAEP.defaultOAEPParams SHA1) key (message vec) -doDecryptionTest key (i, vec) = testCase (show i) (Right (message vec) @=? actual)+doDecryptionTest key i vec = testCase (show i) (Right (message vec) @=? actual)     where actual = OAEP.decrypt Nothing (OAEP.defaultOAEPParams SHA1) key (cipherText vec)  oaepTests = testGroup "RSA-OAEP"     [ testGroup "internal"-        [ doEncryptionTest (private_pub rsaKeyInt) (0 :: Int, vectorInt)-        , doDecryptionTest rsaKeyInt (0 :: Int, vectorInt)+        [ doEncryptionTest (private_pub rsaKeyInt) (0 :: Int) vectorInt+        , doDecryptionTest rsaKeyInt (0 :: Int) vectorInt         ]-    , testGroup "encryption key 1024 bits" $ map (doEncryptionTest $ private_pub rsaKey1) (zip [katZero..] vectorsKey1)-    , testGroup "decryption key 1024 bits" $ map (doDecryptionTest rsaKey1) (zip [katZero..] vectorsKey1)+    , testGroup "encryption key 1024 bits" $ zipWith (doEncryptionTest $ private_pub rsaKey1) [katZero..] vectorsKey1+    , testGroup "decryption key 1024 bits" $ zipWith (doDecryptionTest rsaKey1) [katZero..] vectorsKey1     ]
tests/KAT_PubKey/P256.hs view
@@ -54,6 +54,9 @@ unP256 :: P256Scalar -> Integer unP256 (P256Scalar r) = r +modP256Scalar :: P256Scalar -> P256Scalar+modP256Scalar (P256Scalar r) = P256Scalar (r `mod` curveN)+ p256ScalarToInteger :: P256.Scalar -> Integer p256ScalarToInteger s = os2ip (P256.scalarToBinary s :: Bytes) @@ -92,10 +95,28 @@             let v = unP256 r `mod` curveN                 v' = P256.scalarSub (unP256Scalar r) P256.scalarZero              in v `propertyEq` p256ScalarToInteger v'+        , testProperty "mul" $ \r1 r2 ->+            let r = (unP256 r1 * unP256 r2) `mod` curveN+                r' = P256.scalarMul (unP256Scalar r1) (unP256Scalar r2)+             in r `propertyEq` p256ScalarToInteger r'         , testProperty "inv" $ \r' ->             let inv  = inverseCoprimes (unP256 r') curveN                 inv' = P256.scalarInv (unP256Scalar r')-             in if unP256 r' == 0 then True else inv `propertyEq` p256ScalarToInteger inv'+             in unP256 r' /= 0 ==> inv `propertyEq` p256ScalarToInteger inv'+        , testProperty "inv-safe" $ \r' ->+            let inv  = P256.scalarInv (unP256Scalar r')+                inv' = P256.scalarInvSafe (unP256Scalar r')+             in unP256 r' /= 0 ==> inv `propertyEq` inv'+        , testProperty "inv-safe-mul" $ \r' ->+            let inv = P256.scalarInvSafe (unP256Scalar r')+                res = P256.scalarMul (unP256Scalar r') inv+             in unP256 r' /= 0 ==> 1 `propertyEq` p256ScalarToInteger res+        , testProperty "inv-safe-zero" $+            let inv0 = P256.scalarInvSafe P256.scalarZero+                invN = P256.scalarInvSafe P256.scalarN+             in propertyHold [ eqTest "scalarZero" P256.scalarZero inv0+                             , eqTest "scalarN"    P256.scalarZero invN+                             ]         ]     , testGroup "point"         [ testProperty "marshalling" $ \rx ry ->@@ -115,9 +136,16 @@                 t = P256.pointFromIntegers (xT, yT)                 r = P256.pointFromIntegers (xR, yR)              in r @=? P256.pointAdd s t-        , testProperty "lift-to-curve" $ propertyLiftToCurve-        , testProperty "point-add" $ propertyPointAdd-        , testProperty "point-negate" $ propertyPointNegate+        , testProperty "lift-to-curve" propertyLiftToCurve+        , testProperty "point-add" propertyPointAdd+        , testProperty "point-negate" propertyPointNegate+        , testProperty "point-mul" propertyPointMul+        , testProperty "infinity" $+            let gN = P256.toPoint P256.scalarN+                g1 = P256.pointBase+             in propertyHold [ eqTest "zero" True  (P256.pointIsAtInfinity gN)+                             , eqTest "base" False (P256.pointIsAtInfinity g1)+                             ]         ]     ]   where@@ -146,4 +174,15 @@         let p  = P256.toPoint (unP256Scalar r)             pe = ECC.pointMul curve (unP256 r) curveGen             pR = P256.pointNegate p-         in ECC.pointNegate curve pe `propertyEq` (pointP256ToECC pR)+         in ECC.pointNegate curve pe `propertyEq` pointP256ToECC pR++    propertyPointMul s' r' =+        let s     = modP256Scalar s'+            r     = modP256Scalar r'+            p     = P256.toPoint (unP256Scalar r)+            pe    = ECC.pointMul curve (unP256 r) curveGen+            pR    = P256.toPoint (P256.scalarMul (unP256Scalar s) (unP256Scalar r))+            peR   = ECC.pointMul curve (unP256 s) pe+         in propertyHold [ eqTest "p256" pR (P256.pointMul (unP256Scalar s) p)+                         , eqTest "ecc" peR (pointP256ToECC pR)+                         ]
tests/KAT_PubKey/PSS.hs view
@@ -326,23 +326,23 @@         }     ] -doSignTest key (i, vector) = testCase (show i) (Right (signature vector) @=? actual)+doSignTest key i vector = testCase (show i) (Right (signature vector) @=? actual)     where actual = PSS.signWithSalt (salt vector) Nothing PSS.defaultPSSParamsSHA1 key (message vector) -doVerifyTest key (i, vector) = testCase (show i) (True @=? actual)+doVerifyTest key i vector = testCase (show i) (True @=? actual)     where actual = PSS.verify PSS.defaultPSSParamsSHA1 (private_pub key) (message vector) (signature vector)  pssTests = testGroup "RSA-PSS"     [ testGroup "signature internal"-        [ doSignTest rsaKeyInt (katZero, vectorInt) ]+        [ doSignTest rsaKeyInt katZero vectorInt ]     , testGroup "verify internal"-        [ doVerifyTest rsaKeyInt (katZero, vectorInt) ]-    , testGroup "signature key 1024" $ map (doSignTest rsaKey1) (zip [katZero..] vectorsKey1)-    , testGroup "verify key 1024" $ map (doVerifyTest rsaKey1) (zip [katZero..] vectorsKey1)-    , testGroup "signature key 1025" $ map (doSignTest rsaKey2) (zip [katZero..] vectorsKey2)-    , testGroup "verify key 1025" $ map (doVerifyTest rsaKey2) (zip [katZero..] vectorsKey2)-    , testGroup "signature key 1026" $ map (doSignTest rsaKey3) (zip [katZero..] vectorsKey3)-    , testGroup "verify key 1026" $ map (doVerifyTest rsaKey3) (zip [katZero..] vectorsKey3)-    , testGroup "signature key 1031" $ map (doSignTest rsaKey8) (zip [katZero..] vectorsKey8)-    , testGroup "verify key 1031" $ map (doVerifyTest rsaKey8) (zip [katZero..] vectorsKey8)+        [ doVerifyTest rsaKeyInt katZero vectorInt ]+    , testGroup "signature key 1024" $ zipWith (doSignTest rsaKey1) [katZero..] vectorsKey1+    , testGroup "verify key 1024" $ zipWith (doVerifyTest rsaKey1) [katZero..] vectorsKey1+    , testGroup "signature key 1025" $ zipWith (doSignTest rsaKey2) [katZero..] vectorsKey2+    , testGroup "verify key 1025" $ zipWith (doVerifyTest rsaKey2) [katZero..] vectorsKey2+    , testGroup "signature key 1026" $ zipWith (doSignTest rsaKey3) [katZero..] vectorsKey3+    , testGroup "verify key 1026" $ zipWith (doVerifyTest rsaKey3) [katZero..] vectorsKey3+    , testGroup "signature key 1031" $ zipWith (doSignTest rsaKey8) [katZero..] vectorsKey8+    , testGroup "verify key 1031" $ zipWith (doVerifyTest rsaKey8) [katZero..] vectorsKey8     ]
tests/KAT_PubKey/RSA.hs view
@@ -86,17 +86,17 @@ vectorHasSignature :: VectorRSA -> Bool vectorHasSignature = isRight . sig -doSignatureTest (i, vector) = testCase (show i) (expected @=? actual)+doSignatureTest i vector = testCase (show i) (expected @=? actual)     where expected = sig vector           actual   = RSA.sign Nothing (Just SHA1) (vectorToPrivate vector) (msg vector) -doVerifyTest (i, vector) = testCase (show i) (True @=? actual)+doVerifyTest i vector = testCase (show i) (True @=? actual)     where actual = RSA.verify (Just SHA1) (vectorToPublic vector) (msg vector) bs           Right bs = sig vector  rsaTests = testGroup "RSA"     [ testGroup "SHA1"-        [ testGroup "signature" $ map doSignatureTest (zip [katZero..] vectorsSHA1)-        , testGroup "verify" $ map doVerifyTest $ filter (vectorHasSignature . snd) (zip [katZero..] vectorsSHA1)+        [ testGroup "signature" $ zipWith doSignatureTest [katZero..] vectorsSHA1+        , testGroup "verify" $ zipWith doVerifyTest [katZero..] $ filter vectorHasSignature vectorsSHA1         ]     ]
tests/KAT_PubKey/Rabin.hs view
@@ -95,51 +95,51 @@         }        ] -doBasicRabinEncryptTest key (i, vector) = testCase (show i) (Right (cipherText vector) @=? actual)+doBasicRabinEncryptTest key i vector = testCase (show i) (Right (cipherText vector) @=? actual)     where actual = BRabin.encryptWithSeed (seed vector) (OAEP.defaultOAEPParams SHA1) key (plainText vector) -doBasicRabinDecryptTest key (i, vector) = testCase (show i) (Just (plainText vector) @=? actual)+doBasicRabinDecryptTest key i vector = testCase (show i) (Just (plainText vector) @=? actual)     where actual = BRabin.decrypt (OAEP.defaultOAEPParams SHA1) key (cipherText vector) -doBasicRabinSignTest key (i, vector) = testCase (show i) (Right (BRabin.Signature ((os2ip $ padding vector), (signature vector))) @=? actual)+doBasicRabinSignTest key i vector = testCase (show i) (Right (BRabin.Signature ((os2ip $ padding vector), (signature vector))) @=? actual)     where actual = BRabin.signWith (padding vector) key SHA1 (message vector) -doBasicRabinVerifyTest key (i, vector) = testCase (show i) (True @=? actual)+doBasicRabinVerifyTest key i vector = testCase (show i) (True @=? actual)     where actual = BRabin.verify key SHA1 (message vector) (BRabin.Signature ((os2ip $ padding vector), (signature vector))) -doModifiedRabinSignTest key (i, vector) = testCase (show i) (Right (signature vector) @=? actual)+doModifiedRabinSignTest key i vector = testCase (show i) (Right (signature vector) @=? actual)     where actual = MRabin.sign key SHA1 (message vector) -doModifiedRabinVerifyTest key (i, vector) = testCase (show i) (True @=? actual)+doModifiedRabinVerifyTest key i vector = testCase (show i) (True @=? actual)     where actual = MRabin.verify key SHA1 (message vector) (signature vector) -doRwEncryptTest key (i, vector) = testCase (show i) (Right (cipherText vector) @=? actual)-    where actual = RW.encryptWithSeed (seed vector) (OAEP.defaultOAEPParams SHA1) key (plainText vector) +doRwEncryptTest key i vector = testCase (show i) (Right (cipherText vector) @=? actual)+    where actual = RW.encryptWithSeed (seed vector) (OAEP.defaultOAEPParams SHA1) key (plainText vector) -doRwDecryptTest key (i, vector) = testCase (show i) (Just (plainText vector) @=? actual)+doRwDecryptTest key i vector = testCase (show i) (Just (plainText vector) @=? actual)     where actual = RW.decrypt (OAEP.defaultOAEPParams SHA1) key (cipherText vector) -doRwSignTest key (i, vector) = testCase (show i) (Right (signature vector) @=? actual)+doRwSignTest key i vector = testCase (show i) (Right (signature vector) @=? actual)     where actual = RW.sign key SHA1 (message vector) -doRwVerifyTest key (i, vector) = testCase (show i) (True @=? actual)+doRwVerifyTest key i vector = testCase (show i) (True @=? actual)     where actual = RW.verify key SHA1 (message vector) (signature vector)  rabinTests = testGroup "Rabin"     [ testGroup "Basic"-        [ testGroup "encrypt" $ map (doBasicRabinEncryptTest $ BRabin.private_pub basicRabinKey) (zip [katZero..] basicRabinEncryptionVectors)-        , testGroup "decrypt" $ map (doBasicRabinDecryptTest $ basicRabinKey) (zip [katZero..] basicRabinEncryptionVectors)-        , testGroup "sign" $ map (doBasicRabinSignTest $ basicRabinKey) (zip [katZero..] basicRabinSignatureVectors)-        , testGroup "verify" $ map (doBasicRabinVerifyTest $ BRabin.private_pub basicRabinKey) (zip [katZero..] basicRabinSignatureVectors)+        [ testGroup "encrypt" $ zipWith (doBasicRabinEncryptTest $ BRabin.private_pub basicRabinKey) [katZero..] basicRabinEncryptionVectors+        , testGroup "decrypt" $ zipWith (doBasicRabinDecryptTest basicRabinKey) [katZero..] basicRabinEncryptionVectors+        , testGroup "sign" $ zipWith (doBasicRabinSignTest basicRabinKey) [katZero..] basicRabinSignatureVectors+        , testGroup "verify" $ zipWith (doBasicRabinVerifyTest $ BRabin.private_pub basicRabinKey) [katZero..] basicRabinSignatureVectors         ]     , testGroup "Modified"-        [ testGroup "sign" $ map (doModifiedRabinSignTest $ modifiedRabinKey) (zip [katZero..] modifiedRabinSignatureVectors)-        , testGroup "verify" $ map (doModifiedRabinVerifyTest $ MRabin.private_pub modifiedRabinKey) (zip [katZero..] modifiedRabinSignatureVectors)+        [ testGroup "sign" $ zipWith (doModifiedRabinSignTest modifiedRabinKey) [katZero..] modifiedRabinSignatureVectors+        , testGroup "verify" $ zipWith (doModifiedRabinVerifyTest $ MRabin.private_pub modifiedRabinKey) [katZero..] modifiedRabinSignatureVectors         ]     , testGroup "RW"-        [ testGroup "encrypt" $ map (doRwEncryptTest $ RW.private_pub rwKey) (zip [katZero..] rwEncryptionVectors)-        , testGroup "decrypt" $ map (doRwDecryptTest $ rwKey) (zip [katZero..] rwEncryptionVectors)-        , testGroup "sign" $ map (doRwSignTest $ rwKey) (zip [katZero..] rwSignatureVectors)-        , testGroup "verify" $ map (doRwVerifyTest $ RW.private_pub rwKey) (zip [katZero..] rwSignatureVectors)+        [ testGroup "encrypt" $ zipWith (doRwEncryptTest $ RW.private_pub rwKey) [katZero..] rwEncryptionVectors+        , testGroup "decrypt" $ zipWith (doRwDecryptTest rwKey) [katZero..] rwEncryptionVectors+        , testGroup "sign" $ zipWith (doRwSignTest rwKey) [katZero..] rwSignatureVectors+        , testGroup "verify" $ zipWith (doRwVerifyTest $ RW.private_pub rwKey) [katZero..] rwSignatureVectors         ]     ]
tests/KAT_RC4.hs view
@@ -27,8 +27,8 @@     ]  tests = testGroup "RC4"-    $ map toKatTest $ zip is vectors-  where toKatTest (i, (key, plainText, cipherText)) =+    $ zipWith toKatTest is vectors+  where toKatTest i (key, plainText, cipherText) =             testCase (show i) (cipherText @=? snd (RC4.combine (RC4.initialize key) plainText))         is :: [Int]         is = [1..]
tests/KAT_Scrypt.hs view
@@ -28,6 +28,6 @@     ]  tests = testGroup "Scrypt"-    $ map toCase $ zip [(1::Int)..] vectors-  where toCase (i, ((pass,salt,n,r,p,dklen), output)) =+    $ zipWith toCase [(1::Int)..] vectors+  where toCase i ((pass,salt,n,r,p,dklen), output) =             testCase (show i) (output @=? Scrypt.generate (Scrypt.Parameters n r p dklen) pass salt)
tests/Number.hs view
@@ -10,6 +10,7 @@ import qualified Crypto.Number.Serialize    as BE import qualified Crypto.Number.Serialize.LE as LE import Crypto.Number.Prime+import Crypto.Number.ModArithmetic import Data.Bits  serializationVectors :: [(Int, Integer, ByteString)]@@ -55,6 +56,17 @@     , testProperty "as-power-of-2-and-odd" $ \n ->         let (e, a1) = asPowerOf2AndOdd n          in n == (2^e)*a1+    , testProperty "squareRoot" $ \testDRG (Int0_2901 baseBits') -> do+        let baseBits = baseBits' `mod` 500+            bits = 5 + baseBits -- generating lower than 5 bits causes an error ..+            p = withTestDRG testDRG $ generatePrime bits+        g <- choose (1, p - 1)+        let square x = (x * x) `mod` p+            r = square <$> squareRoot p g+        case jacobi g p of+            Just   1  -> return $ Just g `assertEq` r+            Just (-1) -> return $ Nothing `assertEq` r+            _         -> error "invalid jacobi result"     , testProperty "marshalling-be" $ \qaInt ->         getQAInteger qaInt == BE.os2ip (BE.i2osp (getQAInteger qaInt) :: Bytes)     , testProperty "marshalling-le" $ \qaInt ->@@ -67,9 +79,9 @@         getQAInteger qaInt == BE.os2ip (B.reverse (LE.i2osp (getQAInteger qaInt) :: Bytes))     , testProperty "le-rev-be-40" $ \qaInt ->         getQAInteger qaInt == BE.os2ip (B.reverse (LE.i2ospOf_ 40 (getQAInteger qaInt) :: Bytes))-    , testGroup "marshalling-kat-to-bytearray" $ map toSerializationKat $ zip [katZero..] serializationVectors-    , testGroup "marshalling-kat-to-integer" $ map toSerializationKatInteger $ zip [katZero..] serializationVectors+    , testGroup "marshalling-kat-to-bytearray" $ zipWith toSerializationKat [katZero..] serializationVectors+    , testGroup "marshalling-kat-to-integer" $ zipWith toSerializationKatInteger [katZero..] serializationVectors     ]   where-    toSerializationKat (i, (sz, n, ba)) = testCase (show i) (ba @=? BE.i2ospOf_ sz n)-    toSerializationKatInteger (i, (_, n, ba)) = testCase (show i) (n @=? BE.os2ip ba)+    toSerializationKat i (sz, n, ba) = testCase (show i) (ba @=? BE.i2ospOf_ sz n)+    toSerializationKatInteger i (_, n, ba) = testCase (show i) (n @=? BE.os2ip ba)
tests/Number/F2m.hs view
@@ -2,6 +2,7 @@  import Imports hiding ((.&.)) import Data.Bits+import Data.Maybe import Crypto.Number.Basic (log2) import Crypto.Number.F2m @@ -52,8 +53,34 @@ squareTests = testGroup "squareF2m"     [ testProperty "sqr(a) == a * a"         $ \(Positive m) (NonNegative a) -> mulF2m m a a == squareF2m m a+    -- disabled because we require @m@ to be a suitable modulus and there is no+    -- way to guarantee this+    -- , testProperty "sqrt(a) * sqrt(a) = a"+    --     $ \(Positive m) (NonNegative aa) -> let a = sqrtF2m m aa in mulF2m m a a == modF2m m aa+    , testProperty "sqrt(a) * sqrt(a) = a in GF(2^16)"+        $ let m = 65581 :: Integer -- x^16 + x^5 + x^3 + x^2 + 1+              nums = [0 .. 65535 :: Integer]+          in  nums == [let y = sqrtF2m m x in squareF2m m y | x <- nums]     ] +powTests = testGroup "powF2m"+    [ testProperty "2 is square"+        $ \(Positive m) (NonNegative a) -> powF2m m a 2 == squareF2m m a+    , testProperty "1 is identity"+        $ \(Positive m) (NonNegative a) -> powF2m m a 1 == modF2m m a+    , testProperty "0 is annihilator"+        $ \(Positive m) (NonNegative a) -> powF2m m a 0 == modF2m m 1+    , testProperty "(a * b) ^ c == (a ^ c) * (b ^ c)"+        $ \(Positive m) (NonNegative a) (NonNegative b) (NonNegative c)+            -> powF2m m (mulF2m m a b) c == mulF2m m (powF2m m a c) (powF2m m b c)+    , testProperty "a ^ (b + c) == (a ^ b) * (a ^ c)"+        $ \(Positive m) (NonNegative a) (NonNegative b) (NonNegative c)+            -> powF2m m a (b + c) == mulF2m m (powF2m m a b) (powF2m m a c)+    , testProperty "a ^ (b * c) == (a ^ b) ^ c"+        $ \(Positive m) (NonNegative a) (NonNegative b) (NonNegative c)+            -> powF2m m a (b * c) == powF2m m (powF2m m a b) c+    ]+ invTests = testGroup "invF2m"     [ testProperty "1 / a * a == 1"         $ \(Positive m) (NonNegative a)@@ -70,7 +97,7 @@             -> divF2m m a b == (mulF2m m a <$> invF2m m b)     , testProperty "a * b / b == a"         $ \(Positive m) (NonNegative a) (NonNegative b)-            -> invF2m m b == Nothing || divF2m m (mulF2m m a b) b == Just (modF2m m a)+            -> isNothing (invF2m m b) || divF2m m (mulF2m m a b) b == Just (modF2m m a)     ]  tests = testGroup "number.F2m"@@ -78,6 +105,7 @@     , modTests     , mulTests     , squareTests+    , powTests     , invTests     , divTests     ]
tests/Padding.hs view
@@ -33,6 +33,6 @@                                          ]  tests = testGroup "Padding"-    [ testGroup "Cases" $ map (uncurry testPad) (zip [1..] cases)-    , testGroup "ZeroCases" $ map (uncurry testZeroPad) (zip [1..] zeroCases)+    [ testGroup "Cases" $ zipWith testPad [1..] cases+    , testGroup "ZeroCases" $ zipWith testZeroPad [1..] zeroCases     ]
tests/Salsa.hs view
@@ -37,7 +37,7 @@  tests = testGroup "Salsa"     [ testGroup "KAT" $-        map (\(i,f) -> testCase (show (i :: Int)) f) $ zip [1..] $ map (\(r, k,i,e) -> salsaRunSimple e r k i) vectors+        zipWith (\i (r,k,n,e) -> testCase (show (i :: Int)) $ salsaRunSimple e r k n) [1..] vectors     , testProperty "generate-combine" salsaGenerateCombine     , testProperty "chunking-generate" salsaGenerateChunks     , testProperty "chunking-combine" salsaCombineChunks
tests/Tests.hs view
@@ -3,12 +3,15 @@  import Imports +import Crypto.System.CPU+ import qualified Number import qualified Number.F2m import qualified BCrypt import qualified BCryptPBKDF import qualified ECC import qualified ECC.Edwards25519+import qualified ECDSA import qualified Hash import qualified Poly1305 import qualified Salsa@@ -31,6 +34,7 @@ import qualified KAT_Scrypt -- symmetric cipher -------------------- import qualified KAT_AES+import qualified KAT_AESGCMSIV import qualified KAT_Blowfish import qualified KAT_CAST5 import qualified KAT_Camellia@@ -43,7 +47,10 @@ import qualified Padding  tests = testGroup "cryptonite"-    [ Number.tests+    [ testGroup "runtime"+        [ testCaseInfo "CPU" (return $ show processorOptions)+        ]+    , Number.tests     , Number.F2m.tests     , Hash.tests     , Padding.tests@@ -72,6 +79,7 @@         ]     , testGroup "block-cipher"         [ KAT_AES.tests+        , KAT_AESGCMSIV.tests         , KAT_Blowfish.tests         , KAT_CAST5.tests         , KAT_Camellia.tests@@ -89,6 +97,7 @@     , KAT_AFIS.tests     , ECC.tests     , ECC.Edwards25519.tests+    , ECDSA.tests     ]  main = defaultMain tests
tests/Utils.hs view
@@ -19,7 +19,7 @@     deriving (Show,Eq)  instance Arbitrary TestDRG where-    arbitrary = TestDRG `fmap` arbitrary+    arbitrary = TestDRG `fmap` arbitrary  -- distribution not uniform  withTestDRG (TestDRG l) f = fst $ withDRG (drgNewTest l) f 
tests/XSalsa.hs view
@@ -98,11 +98,31 @@        , "\xB2\xB7\x95\xFE\x6C\x1D\x4C\x83\xC1\x32\x7E\x01\x5A\x67\xD4\x46\x5F\xD8\xE3\x28\x13\x57\x5C\xBA\xB2\x63\xE2\x0E\xF0\x58\x64\xD2\xDC\x17\xE0\xE4\xEB\x81\x43\x6A\xDF\xE9\xF6\x38\xDC\xC1\xC8\xD7\x8F\x6B\x03\x06\xBA\xF9\x38\xE5\xD2\xAB\x0B\x3E\x05\xE7\x35\xCC\x6F\xFF\x2D\x6E\x02\xE3\xD6\x04\x84\xBE\xA7\xC7\xA8\xE1\x3E\x23\x19\x7F\xEA\x7B\x04\xD4\x7D\x48\xF4\xA4\xE5\x94\x41\x74\x53\x94\x92\x80\x0D\x3E\xF5\x1E\x2E\xE5\xE4\xC8\xA0\xBD\xF0\x50\xC2\xDD\x3D\xD7\x4F\xCE\x5E\x7E\x5C\x37\x36\x4F\x75\x47\xA1\x14\x80\xA3\x06\x3B\x9A\x0A\x15\x7B\x15\xB1\x0A\x5A\x95\x4D\xE2\x73\x1C\xED\x05\x5A\xA2\xE2\x76\x7F\x08\x91\xD4\x32\x9C\x42\x6F\x38\x08\xEE\x86\x7B\xED\x0D\xC7\x5B\x59\x22\xB7\xCF\xB8\x95\x70\x0F\xDA\x01\x61\x05\xA4\xC7\xB7\xF0\xBB\x90\xF0\x29\xF6\xBB\xCB\x04\xAC\x36\xAC\x16")      ] +-- Test vector from paper "Cryptography in NaCl"+vectorsCB :: [Vector]+vectorsCB =+    [ ( 20+       , "\x4A\x5D\x9D\x5B\xA4\xCE\x2D\xE1\x72\x8E\x3B\xF4\x80\x35\x0F\x25\xE0\x7E\x21\xC9\x47\xD1\x9E\x33\x76\xF0\x9B\x3C\x1E\x16\x17\x42"+       , "\x69\x69\x6E\xE9\x55\xB6\x2B\x73\xCD\x62\xBD\xA8\x75\xFC\x73\xD6\x82\x19\xE0\x03\x6B\x7A\x0B\x37"+       , "\xBE\x07\x5F\xC5\x3C\x81\xF2\xD5\xCF\x14\x13\x16\xEB\xEB\x0C\x7B\x52\x28\xC5\x2A\x4C\x62\xCB\xD4\x4B\x66\x84\x9B\x64\x24\x4F\xFC\xE5\xEC\xBA\xAF\x33\xBD\x75\x1A\x1A\xC7\x28\xD4\x5E\x6C\x61\x29\x6C\xDC\x3C\x01\x23\x35\x61\xF4\x1D\xB6\x6C\xCE\x31\x4A\xDB\x31\x0E\x3B\xE8\x25\x0C\x46\xF0\x6D\xCE\xEA\x3A\x7F\xA1\x34\x80\x57\xE2\xF6\x55\x6A\xD6\xB1\x31\x8A\x02\x4A\x83\x8F\x21\xAF\x1F\xDE\x04\x89\x77\xEB\x48\xF5\x9F\xFD\x49\x24\xCA\x1C\x60\x90\x2E\x52\xF0\xA0\x89\xBC\x76\x89\x70\x40\xE0\x82\xF9\x37\x76\x38\x48\x64\x5E\x07\x05"+       , "\x8E\x99\x3B\x9F\x48\x68\x12\x73\xC2\x96\x50\xBA\x32\xFC\x76\xCE\x48\x33\x2E\xA7\x16\x4D\x96\xA4\x47\x6F\xB8\xC5\x31\xA1\x18\x6A\xC0\xDF\xC1\x7C\x98\xDC\xE8\x7B\x4D\xA7\xF0\x11\xEC\x48\xC9\x72\x71\xD2\xC2\x0F\x9B\x92\x8F\xE2\x27\x0D\x6F\xB8\x63\xD5\x17\x38\xB4\x8E\xEE\xE3\x14\xA7\xCC\x8A\xB9\x32\x16\x45\x48\xE5\x26\xAE\x90\x22\x43\x68\x51\x7A\xCF\xEA\xBD\x6B\xB3\x73\x2B\xC0\xE9\xDA\x99\x83\x2B\x61\xCA\x01\xB6\xDE\x56\x24\x4A\x9E\x88\xD5\xF9\xB3\x79\x73\xF6\x22\xA4\x3D\x14\xA6\x59\x9B\x1F\x65\x4C\xB4\x5A\x74\xE3\x55\xA5")+    ]+ tests = testGroup "XSalsa"     [ testGroup "KAT" $-        map (\(i,f) -> testCase (show (i :: Int)) f) $ zip [1..] $ map (\(r, k, i, p, e) -> salsaRunSimple r k i p e) vectors+        zipWith (\i (r, k, n, p, e) -> testCase (show (i :: Int)) $ salsaRunSimple r k n p e) [1..] vectors+    , testGroup "crypto_box encryption" $+        zipWith (\i (r, k, n, p, e) -> testCase (show (i :: Int)) $ cryptoBoxEnc r k n p e) [1..] vectorsCB     ]   where       salsaRunSimple rounds key nonce plain expected =           let salsa = XSalsa.initialize rounds key nonce           in fst (XSalsa.combine salsa plain) @?= expected++      cryptoBoxEnc rounds shared nonce plain expected =+          let zero        = B.replicate 16 0+              (iv0, iv1)  = B.splitAt 8 nonce+              salsa0      = XSalsa.initialize rounds shared (zero `B.append` iv0)+              salsa1      = XSalsa.derive salsa0 iv1+              (_, salsa2) = XSalsa.generate salsa1 32 :: (B.ByteString, XSalsa.State)+          in fst (XSalsa.combine salsa2 plain) @?= expected