packages feed

crypton-2.3.1 / Crypto / PubKey / Ed25519.hs

{-# LANGUAGE BangPatterns #-}{-# LANGUAGE GeneralizedNewtypeDeriving #-}-- |-- Module      : Crypto.PubKey.Ed25519-- License     : BSD-style-- Maintainer  : Vincent Hanquez <vincent@snarc.org>-- Stability   : experimental-- Portability : unknown---- Ed25519 supportmodule Crypto.PubKey.Ed25519 (    SecretKey,    PublicKey,    Signature,    -- * Size constants    publicKeySize,    secretKeySize,    signatureSize,    -- * Smart constructors    signature,    publicKey,    secretKey,    -- * Methods    toPublic,    sign,    unsafeSign,    verify,    generateSecretKey,) whereimport Crypto.Debug (DebugShow (..), debugShowBytes)import Data.Wordimport Foreign.C.Typesimport Foreign.Ptrimport Crypto.Errorimport Crypto.Internal.ByteArray (    ByteArrayAccess,    Bytes,    ScrubbedBytes,    withByteArray, )import qualified Crypto.Internal.ByteArray as Bimport Crypto.Internal.Compatimport Crypto.Internal.Importsimport Crypto.Random-- | An Ed25519 Secret keynewtype SecretKey = SecretKey ScrubbedBytes    deriving (Show, Eq, ByteArrayAccess, NFData)instance DebugShow SecretKey where    debugShow = debugShowBytes "SecretKey"-- | An Ed25519 public keynewtype PublicKey = PublicKey Bytes    deriving (Show, Eq, ByteArrayAccess, NFData)-- | An Ed25519 signaturenewtype Signature = Signature Bytes    deriving (Show, Eq, ByteArrayAccess, NFData)-- | Try to build a public key from a bytearraypublicKey :: ByteArrayAccess ba => ba -> CryptoFailable PublicKeypublicKey bs    | B.length bs == publicKeySize =        CryptoPassed $ PublicKey $ B.copyAndFreeze bs (\_ -> return ())    | otherwise =        CryptoFailed $ CryptoError_PublicKeySizeInvalid-- | Try to build a secret key from a bytearraysecretKey :: ByteArrayAccess ba => ba -> CryptoFailable SecretKeysecretKey bs    | B.length bs == secretKeySize = unsafeDoIO $ withByteArray bs initialize    | otherwise =        CryptoFailed CryptoError_SecretKeyStructureInvalid  where    initialize inp = do        valid <- isValidPtr inp        if valid            then (CryptoPassed . SecretKey) <$> B.copy bs (\_ -> return ())            else return $ CryptoFailed CryptoError_SecretKeyStructureInvalid    isValidPtr _ =        return True{-# NOINLINE secretKey #-}-- | Try to build a signature from a bytearraysignature :: ByteArrayAccess ba => ba -> CryptoFailable Signaturesignature bs    | B.length bs == signatureSize =        CryptoPassed $ Signature $ B.copyAndFreeze bs (\_ -> return ())    | otherwise =        CryptoFailed CryptoError_SecretKeyStructureInvalid-- | Create a public key from a secret keytoPublic :: SecretKey -> PublicKeytoPublic (SecretKey sec) = PublicKey    <$> B.allocAndFreeze publicKeySize    $ \result ->        withByteArray sec $ \psec ->            ccrypton_ed25519_publickey psec result{-# NOINLINE toPublic #-}-- | Sign a message using the key pair.--   The public key parameter is ignored and its public key--   is generated from the secret key parameter to prevent--   Double Public Key Signing Function Oracle Attack.sign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> Signaturesign secret _public message =    Signature $ B.allocAndFreeze signatureSize $ \sig ->        withByteArray secret $ \sec ->            withByteArray public $ \pub ->                withByteArray message $ \msg ->                    ccrypton_ed25519_sign msg (fromIntegral msgLen) sec pub sig  where    !msgLen = B.length message    public = toPublic secret-- | Sign a message using the key pair.  This is old `sign`, which is-- vulnerable to private key compromise if the given public key does-- not correspond to the secret key. This function is provided for-- performance critical applications. To use it safely, applications-- must verify or derive the public key.unsafeSign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> SignatureunsafeSign secret public message =    Signature $ B.allocAndFreeze signatureSize $ \sig ->        withByteArray secret $ \sec ->            withByteArray public $ \pub ->                withByteArray message $ \msg ->                    ccrypton_ed25519_sign msg (fromIntegral msgLen) sec pub sig  where    !msgLen = B.length message-- | Verify a messageverify :: ByteArrayAccess ba => PublicKey -> ba -> Signature -> Boolverify public message signatureVal = unsafeDoIO $    withByteArray signatureVal $ \sig ->        withByteArray public $ \pub ->            withByteArray message $ \msg -> do                r <- ccrypton_ed25519_sign_open msg (fromIntegral msgLen) pub sig                return (r == 0)  where    !msgLen = B.length message-- | Generate a secret keygenerateSecretKey :: MonadRandom m => m SecretKeygenerateSecretKey = SecretKey <$> getRandomBytes secretKeySize-- | A public key is 32 bytespublicKeySize :: IntpublicKeySize = 32-- | A secret key is 32 bytessecretKeySize :: IntsecretKeySize = 32-- | A signature is 64 bytessignatureSize :: IntsignatureSize = 64foreign import ccall "crypton_ed25519_publickey"    ccrypton_ed25519_publickey        :: Ptr SecretKey -- secret key        -> Ptr PublicKey -- public key        -> IO ()foreign import ccall "crypton_ed25519_sign_open"    ccrypton_ed25519_sign_open        :: Ptr Word8 -- message        -> CSize -- message len        -> Ptr PublicKey -- public        -> Ptr Signature -- signature        -> IO CIntforeign import ccall "crypton_ed25519_sign"    ccrypton_ed25519_sign        :: Ptr Word8 -- message        -> CSize -- message len        -> Ptr SecretKey -- secret        -> Ptr PublicKey -- public        -> Ptr Signature -- signature        -> IO ()