From 022f16eeef15ac0588cff086b535a8712111e274 Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Sat, 4 Oct 2014 22:37:31 +0100 Subject: [PATCH] While it's probably safe, don't use a "pure" bytestring as a buffer. reallocate a new buffer and copy the old thing inside. --- Crypto/KDF/Scrypt.hs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Crypto/KDF/Scrypt.hs b/Crypto/KDF/Scrypt.hs index bfce230..d6fb9bc 100644 --- a/Crypto/KDF/Scrypt.hs +++ b/Crypto/KDF/Scrypt.hs @@ -16,11 +16,13 @@ module Crypto.KDF.Scrypt import Data.Word import Data.Bits +import Data.Byteable import Data.ByteString (ByteString) import qualified Data.ByteString as B -import Data.Byteable +import qualified Data.ByteString.Internal as B import Foreign.Marshal.Alloc import Foreign.Ptr (Ptr, plusPtr) +import Foreign.ForeignPtr (withForeignPtr) import Control.Monad (forM_) import System.IO.Unsafe @@ -49,14 +51,16 @@ generate params | popCount (n params) /= 1 = error "Scrypt: invalid parameters: n not a power of 2" | otherwise = unsafePerformIO $ do - let b = PBKDF2.generate prf - (PBKDF2.Parameters (password params) (salt params) 1 (p params * 128 * r params)) + let b = PBKDF2.generate prf (PBKDF2.Parameters (password params) (salt params) 1 intLen) + fptr <- B.mallocByteString intLen allocaBytesAligned (128*(fromIntegral $ n params)*(r params)) 8 $ \v -> allocaBytesAligned (256*r params) 8 $ \xy -> - withBytePtr b $ \bPtr -> + withForeignPtr fptr $ \bPtr -> do + withBytePtr b $ \bOrig -> B.memcpy bPtr bOrig intLen forM_ [0..(p params-1)] $ \i -> ccryptonite_scrypt_smix (bPtr `plusPtr` (i * 128 * (r params))) (fromIntegral $ r params) (n params) v xy - return $ PBKDF2.generate prf (PBKDF2.Parameters (password params) b 1 (outputLength params)) - where prf = PBKDF2.prfHMAC SHA256 + return $ PBKDF2.generate prf (PBKDF2.Parameters (password params) (B.PS fptr 0 intLen) 1 (outputLength params)) + where prf = PBKDF2.prfHMAC SHA256 + intLen = p params * 128 * r params