From 41361968f6d840506dcd34d2687216c9d501d1cb Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Sun, 15 Feb 2015 00:13:51 +0000 Subject: [PATCH] add bytes manipulation function --- Crypto/Internal/Bytes.hs | 54 ++++++++++++++++++++++++++++++++++++++++ cryptonite.cabal | 1 + 2 files changed, 55 insertions(+) create mode 100644 Crypto/Internal/Bytes.hs diff --git a/Crypto/Internal/Bytes.hs b/Crypto/Internal/Bytes.hs new file mode 100644 index 0000000..d7a8cf0 --- /dev/null +++ b/Crypto/Internal/Bytes.hs @@ -0,0 +1,54 @@ +-- | +-- Module : Crypto.Internal.Bytes +-- License : BSD-style +-- Maintainer : Vincent Hanquez +-- Stability : experimental +-- Portability : unknown +-- +-- internal helpers function to manipulate sequence of bytes +-- like ByteString and buffer. +-- +module Crypto.Internal.Bytes + ( withByteStringPtr + , tempBufCreate + , bufCreate + , bufXor + ) where + +import Control.Applicative ((<$>), (<*>)) +import Foreign.Ptr (Ptr, plusPtr) +import Foreign.ForeignPtr (withForeignPtr) +import Foreign.Storable (peek, poke) +import Foreign.Marshal.Alloc (allocaBytesAligned) +import Data.ByteString (ByteString) +import Data.ByteString.Internal (ByteString(..), mallocByteString) +import Data.Bits (xor) +import Data.Word (Word8) +import Data.ByteString.Internal (toForeignPtr) + +withByteStringPtr :: ByteString -> (Ptr Word8 -> IO a) -> IO a +withByteStringPtr b f = + withForeignPtr fptr $ \ptr -> f (ptr `plusPtr` off) + where (fptr, off, _) = toForeignPtr b + +-- | Create a buffer, and turns the final resulting ByteString +bufCreate :: Int -> (Ptr Word8 -> IO ()) -> IO ByteString +bufCreate size f = do + fptr <- mallocByteString size + withForeignPtr fptr f + return $! PS fptr 0 size + +-- | Create a new temporary buffer +tempBufCreate :: Int -> (Ptr Word8 -> IO a) -> IO a +tempBufCreate size f = allocaBytesAligned size 8 f + +-- | xor bytes from source1 and source2 to destination +-- +-- d = s1 xor s2 +-- +-- s1, nor s2 are modified unless +bufXor :: Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> Int -> IO () +bufXor _ _ _ 0 = return () +bufXor d s1 s2 n = do + (xor <$> peek s1 <*> peek s2) >>= poke d + bufXor (d `plusPtr` 1) (s1 `plusPtr` 1) (s2 `plusPtr` 1) (n-1) diff --git a/cryptonite.cabal b/cryptonite.cabal index f912839..f46087a 100644 --- a/cryptonite.cabal +++ b/cryptonite.cabal @@ -85,6 +85,7 @@ Library , Crypto.Random.Entropy.Source , Crypto.Random.Entropy.Backend , Crypto.Internal.Compat + , Crypto.Internal.Bytes Build-depends: base >= 4.3 && < 5 , bytestring , securemem >= 0.1.7