packages feed

crypton-2.3.1 / Crypto / PubKey / DSA.hs

{-# LANGUAGE DeriveDataTypeable #-}-- |-- Module      : Crypto.PubKey.DSA-- License     : BSD-style-- Maintainer  : Vincent Hanquez <vincent@snarc.org>-- Stability   : experimental-- Portability : Good---- An implementation of the Digital Signature Algorithm (DSA)---- == What is kept from the clock, and what is not---- Signing keeps the private number and the ephemeral @k@ out of the two-- places whose duration would otherwise follow them: the exponentiation is-- 'Crypto.Number.ModArithmetic.expSafe', which walks the exponent a fixed-- four bits at a time, and @k@ is inverted by Fermat's little theorem rather-- than by the extended Euclidean algorithm, whose number of steps follows the-- bits it is given.---- What is left is the arithmetic around them.  @x * r@, the addition and the-- reduction modulo @q@ are 'Integer' operations, and an 'Integer' costs what-- its size says: a private number that happens to be short is multiplied in-- fewer words than a full-length one.  The same holds in-- "Crypto.PubKey.ElGamal" and "Crypto.PubKey.Rabin.Basic".  Removing it means-- leaving 'Integer' for a fixed-width representation, which is what-- "Crypto.PubKey.RSA" does for its exponentiation and the curve modules do-- throughout; there is nothing a caller can do about it from here.module Crypto.PubKey.DSA (    Params (..),    Signature (..),    PublicKey (..),    PrivateKey (..),    PublicNumber,    PrivateNumber,    -- * Generation    generatePrivate,    calculatePublic,    -- * Signature primitive    sign,    signWith,    signDigest,    signDigestWith,    -- * Deterministic nonces    deterministicNonce,    signDeterministic,    signDigestDeterministic,    -- * Verification primitive    verify,    verifyDigest,    -- * Key pair    KeyPair (..),    toPublicKey,    toPrivateKey,) whereimport Crypto.Debug (DebugShow (..))import Data.Dataimport Crypto.Hashimport Crypto.Internal.ByteArray (ByteArrayAccess, ScrubbedBytes)import qualified Crypto.Internal.ByteArray as Bimport Crypto.Internal.Importsimport Crypto.Number.Generateimport Crypto.Number.ModArithmetic (expFast, expSafe, inverse, inverseSafe)import Crypto.PubKey.Internal (dsaTruncHashDigest, getHashAlg, rfc6979Nonce)import Crypto.Random.Types-- | DSA Public Number, usually embedded in DSA Public Keytype PublicNumber = Integer-- | DSA Private Number, usually embedded in DSA Private Keytype PrivateNumber = Integer-- | Represent DSA parameters namely P, G, and Q.data Params = Params    { params_p :: Integer    -- ^ DSA p    , params_g :: Integer    -- ^ DSA g    , params_q :: Integer    -- ^ DSA q    }    deriving (Show, Read, Eq, Data)instance NFData Params where    rnf (Params p g q) = p `seq` g `seq` q `seq` ()-- | Represent a DSA signature namely R and S.data Signature = Signature    { sign_r :: Integer    -- ^ DSA r    , sign_s :: Integer    -- ^ DSA s    }    deriving (Show, Read, Eq, Data)instance NFData Signature where    rnf (Signature r s) = r `seq` s `seq` ()-- | Represent a DSA public key.data PublicKey = PublicKey    { public_params :: Params    -- ^ DSA parameters    , public_y :: PublicNumber    -- ^ DSA public Y    }    deriving (Show, Read, Eq, Data)instance NFData PublicKey where    rnf (PublicKey params y) = y `seq` params `seq` ()-- | Represent a DSA private key.---- Only x need to be secret.-- the DSA parameters are publicly shared with the other side.data PrivateKey = PrivateKey    { private_params :: Params    -- ^ DSA parameters    , private_x :: PrivateNumber    -- ^ DSA private X    }    deriving (Read, Eq, Data)-- | The parameters are shown; @private_x@ is not.  Use-- 'Crypto.Debug.debugShow' to see it.instance Show PrivateKey where    showsPrec d k =        showParen (d > 10) $            showString "PrivateKey {private_params = "                . shows (private_params k)                . showString ", private_x = <secret>}"instance DebugShow PrivateKey where    debugShow k =        showString "PrivateKey {private_params = "            . shows (private_params k)            . showString ", private_x = "            . shows (private_x k)            . showChar '}'            $ ""instance NFData PrivateKey where    rnf (PrivateKey params x) = x `seq` params `seq` ()-- | Represent a DSA key pairdata KeyPair = KeyPair Params PublicNumber PrivateNumber    deriving (Read, Eq, Data)instance Show KeyPair where    showsPrec d (KeyPair params y _) =        showParen (d > 10) $            showString "KeyPair "                . showsPrec 11 params                . showChar ' '                . showsPrec 11 y                . showString " <secret>"instance DebugShow KeyPair where    debugShow (KeyPair params y x) =        showString "KeyPair "            . showsPrec 11 params            . showChar ' '            . showsPrec 11 y            . showChar ' '            . showsPrec 11 x            $ ""instance NFData KeyPair where    rnf (KeyPair params y x) = x `seq` y `seq` params `seq` ()-- | Public key of a DSA Key pairtoPublicKey :: KeyPair -> PublicKeytoPublicKey (KeyPair params pub _) = PublicKey params pub-- | Private key of a DSA Key pairtoPrivateKey :: KeyPair -> PrivateKeytoPrivateKey (KeyPair params _ priv) = PrivateKey params priv-- | generate a private number with no specific property-- this number is usually called X in DSA text.generatePrivate :: MonadRandom m => Params -> m PrivateNumbergeneratePrivate (Params _ _ q) = generateMax q-- | Calculate the public number from the parameters and the private keycalculatePublic :: Params -> PrivateNumber -> PublicNumbercalculatePublic (Params p g _) x = expSafe g x p-- | sign message using the private key and an explicit k number.signWith    :: (ByteArrayAccess msg, HashAlgorithm hash)    => Integer    -- ^ k random number    -> PrivateKey    -- ^ private key    -> hash    -- ^ hash function    -> msg    -- ^ message to sign    -> Maybe SignaturesignWith k pk hashAlg msg = signDigestWith k pk (hashWith hashAlg msg)-- | Sign a digest using the private key and an explicit k number.---- The digest's type says which algorithm made it, so this needs nothing else-- to name one.  'signWith' takes a @hash@ value and never reads it -- it is-- there to fix the type -- which leaves a caller that is itself polymorphic-- in the algorithm with nothing to pass.signDigestWith    :: HashAlgorithm hash    => Integer    -- ^ k random number    -> PrivateKey    -- ^ private key    -> Digest hash    -- ^ digest of the message to sign    -> Maybe SignaturesignDigestWith k pk digest = do    -- k comes from the caller and is only invertible when it is coprime with    -- q, which the caller cannot check without knowing q is prime.  It is also    -- a secret worth as much as the private key, so it is inverted without    -- the extended Euclidean algorithm, whose steps follow the bits of what    -- it is given    kInv <- inverseSafe k q    let hm = dsaTruncHashDigest digest q        r = expSafe g k p `mod` q        s = (kInv * (hm + x * r)) `mod` q    if r == 0 || s == 0 then Nothing else Just $ Signature r s  where    -- parameters    (Params p g q) = private_params pk    x = private_x pk-- | sign message using the private key.sign    :: (ByteArrayAccess msg, HashAlgorithm hash, MonadRandom m)    => PrivateKey -> hash -> msg -> m Signaturesign pk hashAlg msg = signDigest pk (hashWith hashAlg msg)-- | Sign a digest using the private key.  See 'signDigestWith' for why a-- digest rather than a @hash@ value.---- The nonce is hedged: RFC 6979's, from the private key and the digest,-- with 32 random bytes added as in its section 3.6.  Repeated randomness-- then repeats a nonce only for the same digest, which gives away nothing.signDigest    :: (HashAlgorithm hash, MonadRandom m)    => PrivateKey -> Digest hash -> m SignaturesignDigest pk digest = do    extra <- getRandomBytes 32    return $ nonceWith (getHashAlg digest) pk digest extra $ \k ->        signDigestWith k pk digest-- | Deterministic nonce generation according to RFC 6979.---- The nonce is derived from the private key and the digest alone, so a-- signature made this way needs no random number generator.  The hash used-- to seed the generator is given separately from the one the message was-- digested with, as RFC 6979 allows.  The last argument is what to do with a-- candidate nonce; 'Nothing' draws another.deterministicNonce    :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)    => hashDRG -> PrivateKey -> Digest hashDigest -> (Integer -> Maybe a) -> adeterministicNonce alg pk digest = nonceWith alg pk digest B.emptynonceWith    :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)    => hashDRG    -> PrivateKey    -> Digest hashDigest    -> ScrubbedBytes    -> (Integer -> Maybe a)    -> anonceWith alg pk = rfc6979Nonce alg q (private_x pk)  where    (Params _ _ q) = private_params pk-- | Sign a digest with the nonce of RFC 6979 rather than a random one.signDigestDeterministic    :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)    => hashDRG -> PrivateKey -> Digest hashDigest -> SignaturesignDigestDeterministic alg pk digest =    deterministicNonce alg pk digest $ \k -> signDigestWith k pk digest-- | Sign a message with the nonce of RFC 6979 rather than a random one.signDeterministic    :: (HashAlgorithm hashDRG, HashAlgorithm hash, ByteArrayAccess msg)    => hashDRG -> PrivateKey -> hash -> msg -> SignaturesignDeterministic alg pk hashAlg msg =    signDigestDeterministic alg pk (hashWith hashAlg msg)-- | verify a bytestring using the public key.verify    :: (ByteArrayAccess msg, HashAlgorithm hash)    => hash -> PublicKey -> Signature -> msg -> Boolverify hashAlg pk sig m = verifyDigest pk sig (hashWith hashAlg m)-- | Verify a signature over a digest.  See 'signDigestWith' for why a digest-- rather than a @hash@ value.verifyDigest    :: HashAlgorithm hash => PublicKey -> Signature -> Digest hash -> BoolverifyDigest pk (Signature r s) digest    -- Reject the signature if either 0 < r < q or 0 < s < q is not satisfied.    | r <= 0 || r >= q || s <= 0 || s >= q = False    -- the parameters come from the signer; a modulus below 2 is no group,    -- and p = 0 used to raise divide by zero rather than answer False    | p < 2 = False    -- s is invertible for every 0 < s < q when q is prime, but the parameters    -- arrive with the public key and a composite q admits an s that is not    | otherwise = maybe False (r ==) v  where    (Params p g q) = public_params pk    y = public_y pk    hm = dsaTruncHashDigest digest q    v = do        w <- inverse s q        let u1 = (hm * w) `mod` q            u2 = (r * w) `mod` q        return $ ((expFast g u1 p) * (expFast y u2 p)) `mod` p `mod` q