diff options
Diffstat (limited to 'src/Crypto/Cipher/XSalsa.hs')
-rw-r--r-- | src/Crypto/Cipher/XSalsa.hs | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/Crypto/Cipher/XSalsa.hs b/src/Crypto/Cipher/XSalsa.hs new file mode 100644 index 00000000..494760e2 --- /dev/null +++ b/src/Crypto/Cipher/XSalsa.hs | |||
@@ -0,0 +1,50 @@ | |||
1 | -- | | ||
2 | -- Module : Crypto.Cipher.XSalsa | ||
3 | -- License : BSD-style | ||
4 | -- Maintainer : Brandon Hamilton <brandon.hamilton@gmail.com> | ||
5 | -- Stability : stable | ||
6 | -- Portability : good | ||
7 | -- | ||
8 | -- Implementation of XSalsa20 algorithm | ||
9 | -- <https://cr.yp.to/snuffle/xsalsa-20081128.pdf> | ||
10 | -- Based on the Salsa20 algorithm with 256 bit key extended with 192 bit nonce | ||
11 | |||
12 | {-# LANGUAGE ForeignFunctionInterface #-} | ||
13 | module Crypto.Cipher.XSalsa | ||
14 | ( initialize | ||
15 | , combine | ||
16 | , generate | ||
17 | , State | ||
18 | ) where | ||
19 | |||
20 | import Crypto.Internal.ByteArray (ByteArrayAccess, ByteArray, ScrubbedBytes) | ||
21 | import qualified Crypto.Internal.ByteArray as B | ||
22 | import Crypto.Internal.Compat | ||
23 | import Crypto.Internal.Imports | ||
24 | import Foreign.Ptr | ||
25 | import Foreign.Storable | ||
26 | import Foreign.C.Types | ||
27 | import Crypto.Cipher.Salsa hiding (initialize) | ||
28 | |||
29 | -- | Initialize a new XSalsa context with the number of rounds, | ||
30 | -- the key and the nonce associated. | ||
31 | initialize :: (ByteArrayAccess key, ByteArrayAccess nonce) | ||
32 | => Int -- ^ number of rounds (8,12,20) | ||
33 | -> key -- ^ the key (256 bits) | ||
34 | -> nonce -- ^ the nonce (192 bits) | ||
35 | -> State -- ^ the initial XSalsa state | ||
36 | initialize nbRounds key nonce | ||
37 | | kLen /= 32 = error "XSalsa: key length should be 256 bits" | ||
38 | | nonceLen /= 24 = error "XSalsa: nonce length should be 192 bits" | ||
39 | | not (nbRounds `elem` [8,12,20]) = error "XSalsa: rounds should be 8, 12 or 20" | ||
40 | | otherwise = unsafeDoIO $ do | ||
41 | stPtr <- B.alloc 132 $ \stPtr -> | ||
42 | B.withByteArray nonce $ \noncePtr -> | ||
43 | B.withByteArray key $ \keyPtr -> | ||
44 | ccryptonite_xsalsa_init stPtr (fromIntegral nbRounds) kLen keyPtr nonceLen noncePtr | ||
45 | return $ State stPtr | ||
46 | where kLen = B.length key | ||
47 | nonceLen = B.length nonce | ||
48 | |||
49 | foreign import ccall "cryptonite_xsalsa_init" | ||
50 | ccryptonite_xsalsa_init :: Ptr State -> Int -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> IO () | ||