summaryrefslogtreecommitdiff
path: root/src/Crypto/Cipher/XSalsa.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Crypto/Cipher/XSalsa.hs')
-rw-r--r--src/Crypto/Cipher/XSalsa.hs50
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 #-}
13module Crypto.Cipher.XSalsa
14 ( initialize
15 , combine
16 , generate
17 , State
18 ) where
19
20import Crypto.Internal.ByteArray (ByteArrayAccess, ByteArray, ScrubbedBytes)
21import qualified Crypto.Internal.ByteArray as B
22import Crypto.Internal.Compat
23import Crypto.Internal.Imports
24import Foreign.Ptr
25import Foreign.Storable
26import Foreign.C.Types
27import Crypto.Cipher.Salsa hiding (initialize)
28
29-- | Initialize a new XSalsa context with the number of rounds,
30-- the key and the nonce associated.
31initialize :: (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
36initialize 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
49foreign import ccall "cryptonite_xsalsa_init"
50 ccryptonite_xsalsa_init :: Ptr State -> Int -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> IO ()