aboutsummaryrefslogtreecommitdiffstats
path: root/src/Network/WireGuard/Foreign/Key.hs
blob: 2a0e7b87aab4e3cf240b6f92974f8f0de4eb24fc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module Network.WireGuard.Foreign.Key
  ( Key
  , fromByteString
  , toByteString
  ) where

import qualified Data.ByteString                     as BS

import           Foreign

import           Network.WireGuard.Internal.Constant (keyLength)

newtype Key = Key { fromKey :: [Word8] }

instance Storable Key where
    sizeOf _         = sizeOf (undefined :: Word8) * keyLength
    alignment _      = alignment (undefined :: Word8)
    peek ptr         = Key <$> peekArray keyLength (castPtr ptr)
    poke ptr (Key k)
        | length k == keyLength = pokeArray (castPtr ptr) k
        | otherwise             = error "Key.poke: key length mismatch"

fromByteString :: BS.ByteString -> Key
fromByteString bs
    | BS.length bs == keyLength = Key (BS.unpack bs)
    | otherwise                 = error "Key.fromByteString: key length mismatch"

toByteString :: Key -> BS.ByteString
toByteString = BS.pack . fromKey