poly1305

The Poly1305 message authentication code (docs.ppad.tech/poly1305).
git clone git://git.ppad.tech/poly1305.git
Log | Files | Refs | README | LICENSE

Native.hs (1863B)


      1 {-# OPTIONS_HADDOCK hide #-}
      2 {-# LANGUAGE BangPatterns #-}
      3 
      4 -- |
      5 -- Module: Crypto.MAC.Poly1305.Native
      6 -- Copyright: (c) 2025 Jared Tobin
      7 -- License: MIT
      8 -- Maintainer: Jared Tobin <jared@ppad.tech>
      9 --
     10 -- A native C kernel for the Poly1305 MAC on aarch64 and x86_64, with
     11 -- ARM NEON or x86 AVX2 acceleration.
     12 
     13 module Crypto.MAC.Poly1305.Native (
     14     poly1305_native_available
     15   , mac
     16   ) where
     17 
     18 import qualified Data.ByteString as BS
     19 import qualified Data.ByteString.Internal as BI
     20 import Data.Word (Word8)
     21 import Foreign.C.Types (CInt(..), CSize(..))
     22 import Foreign.ForeignPtr (withForeignPtr)
     23 import Foreign.Ptr (Ptr, plusPtr)
     24 import System.IO.Unsafe (unsafeDupablePerformIO)
     25 
     26 -- ffi ------------------------------------------------------------------------
     27 
     28 foreign import ccall unsafe "poly1305_mac_native"
     29   c_poly1305_mac
     30     :: Ptr Word8 -> Ptr Word8 -> CSize -> Ptr Word8 -> IO ()
     31 
     32 foreign import ccall unsafe "poly1305_native_available"
     33   c_poly1305_native_available :: IO CInt
     34 
     35 -- utilities ------------------------------------------------------------------
     36 
     37 fi :: (Integral a, Num b) => a -> b
     38 fi = fromIntegral
     39 {-# INLINE fi #-}
     40 
     41 -- api ------------------------------------------------------------------------
     42 
     43 -- | Is the native kernel available?
     44 poly1305_native_available :: Bool
     45 poly1305_native_available =
     46   unsafeDupablePerformIO c_poly1305_native_available /= 0
     47 {-# NOINLINE poly1305_native_available #-}
     48 
     49 -- | Compute a Poly1305 MAC over the message using the given (already-
     50 --   validated 32-byte) key.
     51 mac :: BS.ByteString -> BS.ByteString -> BS.ByteString
     52 mac (BI.PS kfp koff _) (BI.PS mfp moff mlen) =
     53   BI.unsafeCreate 16 $ \dst ->
     54     withForeignPtr kfp $ \kp0 ->
     55     withForeignPtr mfp $ \mp0 ->
     56       c_poly1305_mac (kp0 `plusPtr` koff)
     57                      (mp0 `plusPtr` moff)
     58                      (fi mlen)
     59                      dst