{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Encrypted tokens/tickets to keep state in the client side.
module Crypto.Token (
    -- * Configuration
    Config,
    defaultConfig,
    interval,
    tokenLifetime,
    threadName,

    -- * Token manager
    TokenManager,
    spawnTokenManager,
    killTokenManager,

    -- * Encryption and decryption
    encryptToken,
    decryptToken,
) where

import Control.Concurrent
import qualified Control.Exception as E
import Control.Monad (when)
import Crypto.Cipher.AES (AES256)
import Crypto.Cipher.Types (AEADMode (..), AuthTag (..))
import qualified Crypto.Cipher.Types as C
import Crypto.Error (maybeCryptoError, throwCryptoError)
import Crypto.Random (getRandomBytes)
import Data.Array.IO
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.IORef as I
import Data.Word
import GHC.Clock (getMonotonicTimeNSec)
import GHC.Conc.Sync (labelThread)
import Network.ByteOrder

----------------------------------------------------------------

type Index = Word16
type Counter = Word64

-- | Configuration for token manager.
data Config = Config
    { Config -> Int
interval :: Int
    -- ^ The interval to generate a new secret and remove the oldest one in seconds.
    , Config -> Int
tokenLifetime :: Int
    -- ^ The token lifetime in seconds, that is, tokens can be decrypted in this period.
    --   It is cut short if it spans more than 65535 intervals.
    , Config -> String
threadName :: String
    }
    deriving (Config -> Config -> Bool
(Config -> Config -> Bool)
-> (Config -> Config -> Bool) -> Eq Config
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Config -> Config -> Bool
== :: Config -> Config -> Bool
$c/= :: Config -> Config -> Bool
/= :: Config -> Config -> Bool
Eq, Int -> Config -> ShowS
[Config] -> ShowS
Config -> String
(Int -> Config -> ShowS)
-> (Config -> String) -> ([Config] -> ShowS) -> Show Config
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Config -> ShowS
showsPrec :: Int -> Config -> ShowS
$cshow :: Config -> String
show :: Config -> String
$cshowList :: [Config] -> ShowS
showList :: [Config] -> ShowS
Show)

-- | Default configuration to update secrets in 30 minutes (1,800 seconds) and token lifetime is 2 hours (7,200 seconds)
--
-- >>> defaultConfig
-- Config {interval = 1800, tokenLifetime = 7200, threadName = "Crypto token manager"}
defaultConfig :: Config
defaultConfig :: Config
defaultConfig =
    Config
        { interval :: Int
interval = Int
1800
        , tokenLifetime :: Int
tokenLifetime = Int
7200
        , threadName :: String
threadName = String
"Crypto token manager"
        }

----------------------------------------------------------------

-- | The abstract data type for token manager.
data TokenManager = TokenManager
    { TokenManager -> AES256
headerKey :: AES256
    , TokenManager -> IO (Secret, Word16)
getEncryptSecret :: IO (Secret, Index)
    , TokenManager -> Word16 -> IO Secret
getDecryptSecret :: Index -> IO Secret
    , TokenManager -> ThreadId
threadId :: ThreadId
    , TokenManager -> Word64
lifetimeNSec :: Word64
    }

-- | Spawning a token manager.
--   This throws an 'IOError' if 'interval' is not positive.
spawnTokenManager :: Config -> IO TokenManager
spawnTokenManager :: Config -> IO TokenManager
spawnTokenManager Config{Int
String
interval :: Config -> Int
tokenLifetime :: Config -> Int
threadName :: Config -> String
interval :: Int
tokenLifetime :: Int
threadName :: String
..} = do
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
interval Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        IOError -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO (IOError -> IO ()) -> IOError -> IO ()
forall a b. (a -> b) -> a -> b
$
            String -> IOError
userError String
"Crypto.Token: interval must be positive"
    -- the secret a token was made with must outlive the token itself,
    -- and an index travels as Word16, so there are at most 65536 slots
    let lifetime :: Int
lifetime = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 Int
tokenLifetime
        slots :: Int
slots = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min Int
65536 (Int -> Int) -> Int -> Int
forall a b. (a -> b) -> a -> b
$ (Int
lifetime Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
interval Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
interval Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
    emp <- IO Secret
emptySecret
    arr <- newArray (0, slots - 1) emp
    ent <- generateSecret
    writeArray arr 0 ent
    ref <- I.newIORef 0
    tid <- forkIO $ loop arr ref
    labelThread tid threadName
    hkey <- newHeaderKey
    return $
        TokenManager hkey (readCurrentSecret arr ref) (readSecret arr) tid $
            fromIntegral lifetime * 1000000000
  where
    loop :: IOArray Int Secret -> IORef Int -> IO b
loop IOArray Int Secret
arr IORef Int
ref = do
        Int -> IO ()
delaySeconds Int
interval
        -- a failed rotation is retried at the next interval
        IOArray Int Secret -> IORef Int -> IO ()
update IOArray Int Secret
arr IORef Int
ref IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`E.catch` SomeException -> IO ()
ignoreSync
        IOArray Int Secret -> IORef Int -> IO b
loop IOArray Int Secret
arr IORef Int
ref
    ignoreSync :: E.SomeException -> IO ()
    ignoreSync :: SomeException -> IO ()
ignoreSync SomeException
e = case SomeException -> Maybe SomeAsyncException
forall e. Exception e => SomeException -> Maybe e
E.fromException SomeException
e of
        Just (E.SomeAsyncException e
_) -> SomeException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
E.throwIO SomeException
e
        Maybe SomeAsyncException
Nothing -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    update :: IOArray Int Secret -> I.IORef Int -> IO ()
    update :: IOArray Int Secret -> IORef Int -> IO ()
update IOArray Int Secret
arr IORef Int
ref = do
        idx0 <- IORef Int -> IO Int
forall a. IORef a -> IO a
I.readIORef IORef Int
ref
        n <- rangeSize <$> getBounds arr
        let idx = (Int
idx0 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
n
        sec <- generateSecret
        writeArray arr idx sec
        I.writeIORef ref idx

-- threadDelay's microseconds overflow a 32-bit Int after 35 minutes.
delaySeconds :: Int -> IO ()
delaySeconds :: Int -> IO ()
delaySeconds Int
n
    | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    | Bool
otherwise = do
        let m :: Int
m = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min Int
n Int
1000
        Int -> IO ()
threadDelay (Int
m Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1000000)
        Int -> IO ()
delaySeconds (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
m)

-- | Killing a token manager.
killTokenManager :: TokenManager -> IO ()
killTokenManager :: TokenManager -> IO ()
killTokenManager TokenManager{IO (Secret, Word16)
Word64
AES256
ThreadId
Word16 -> IO Secret
headerKey :: TokenManager -> AES256
getEncryptSecret :: TokenManager -> IO (Secret, Word16)
getDecryptSecret :: TokenManager -> Word16 -> IO Secret
threadId :: TokenManager -> ThreadId
lifetimeNSec :: TokenManager -> Word64
headerKey :: AES256
getEncryptSecret :: IO (Secret, Word16)
getDecryptSecret :: Word16 -> IO Secret
threadId :: ThreadId
lifetimeNSec :: Word64
..} = ThreadId -> IO ()
killThread ThreadId
threadId

----------------------------------------------------------------

readSecret :: IOArray Int Secret -> Index -> IO Secret
readSecret :: IOArray Int Secret -> Word16 -> IO Secret
readSecret IOArray Int Secret
secrets Word16
idx0 = do
    n <- (Int, Int) -> Int
forall a. Ix a => (a, a) -> Int
rangeSize ((Int, Int) -> Int) -> IO (Int, Int) -> IO Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOArray Int Secret -> IO (Int, Int)
forall i. Ix i => IOArray i Secret -> IO (i, i)
forall (a :: * -> * -> *) e (m :: * -> *) i.
(MArray a e m, Ix i) =>
a i e -> m (i, i)
getBounds IOArray Int Secret
secrets
    readArray secrets $ fromIntegral idx0 `mod` n

readCurrentSecret :: IOArray Int Secret -> I.IORef Int -> IO (Secret, Index)
readCurrentSecret :: IOArray Int Secret -> IORef Int -> IO (Secret, Word16)
readCurrentSecret IOArray Int Secret
arr IORef Int
ref = do
    idx <- IORef Int -> IO Int
forall a. IORef a -> IO a
I.readIORef IORef Int
ref
    sec <- readArray arr idx
    return (sec, fromIntegral idx)

----------------------------------------------------------------

data Secret = Secret
    { Secret -> ByteString
secretIV :: ByteString
    , Secret -> ByteString
secretKey :: ByteString
    , Secret -> IORef Word64
secretCounter :: I.IORef Counter
    }

emptySecret :: IO Secret
emptySecret :: IO Secret
emptySecret = ByteString -> ByteString -> IORef Word64 -> Secret
Secret ByteString
BS.empty ByteString
BS.empty (IORef Word64 -> Secret) -> IO (IORef Word64) -> IO Secret
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Word64 -> IO (IORef Word64)
forall a. a -> IO (IORef a)
I.newIORef Word64
0

generateSecret :: IO Secret
generateSecret :: IO Secret
generateSecret =
    ByteString -> ByteString -> IORef Word64 -> Secret
Secret
        (ByteString -> ByteString -> IORef Word64 -> Secret)
-> IO ByteString -> IO (ByteString -> IORef Word64 -> Secret)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO ByteString
genIV
        IO (ByteString -> IORef Word64 -> Secret)
-> IO ByteString -> IO (IORef Word64 -> Secret)
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> IO ByteString
genKey
        IO (IORef Word64 -> Secret) -> IO (IORef Word64) -> IO Secret
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Word64 -> IO (IORef Word64)
forall a. a -> IO (IORef a)
I.newIORef Word64
0

genKey :: IO ByteString
genKey :: IO ByteString
genKey = Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
keyLength

genIV :: IO ByteString
genIV :: IO ByteString
genIV = Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
ivLength

----------------------------------------------------------------

-- 96 bits, the nonce length GCM is designed for
ivLength :: Int
ivLength :: Int
ivLength = Int
12

keyLength :: Int
keyLength :: Int
keyLength = Int
32

indexLength :: Int
indexLength :: Int
indexLength = Int
2

counterLength :: Int
counterLength :: Int
counterLength = Int
8

tagLength :: Int
tagLength :: Int
tagLength = Int
16

-- one AES block: index, counter and zero padding
headerLength :: Int
headerLength :: Int
headerLength = Int
16

----------------------------------------------------------------

data Header = Header
    { Header -> Word16
headerIndex :: Index
    , Header -> Word64
headerCounter :: Counter
    }

encodeHeader :: Header -> IO ByteString
encodeHeader :: Header -> IO ByteString
encodeHeader Header{Word16
Word64
headerIndex :: Header -> Word16
headerCounter :: Header -> Word64
headerIndex :: Word16
headerCounter :: Word64
..} = Int -> (WriteBuffer -> IO ()) -> IO ByteString
withWriteBuffer (Int
indexLength Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
counterLength) ((WriteBuffer -> IO ()) -> IO ByteString)
-> (WriteBuffer -> IO ()) -> IO ByteString
forall a b. (a -> b) -> a -> b
$ \WriteBuffer
wbuf -> do
    WriteBuffer -> Word16 -> IO ()
write16 WriteBuffer
wbuf Word16
headerIndex
    WriteBuffer -> Word64 -> IO ()
write64 WriteBuffer
wbuf Word64
headerCounter

decodeHeader :: ByteString -> IO Header
decodeHeader :: ByteString -> IO Header
decodeHeader ByteString
bs = ByteString -> (ReadBuffer -> IO Header) -> IO Header
forall a. ByteString -> (ReadBuffer -> IO a) -> IO a
withReadBuffer ByteString
bs ((ReadBuffer -> IO Header) -> IO Header)
-> (ReadBuffer -> IO Header) -> IO Header
forall a b. (a -> b) -> a -> b
$ \ReadBuffer
rbuf ->
    Word16 -> Word64 -> Header
Header (Word16 -> Word64 -> Header) -> IO Word16 -> IO (Word64 -> Header)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ReadBuffer -> IO Word16
forall a. Readable a => a -> IO Word16
read16 ReadBuffer
rbuf IO (Word64 -> Header) -> IO Word64 -> IO Header
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ReadBuffer -> IO Word64
forall a. Readable a => a -> IO Word64
read64 ReadBuffer
rbuf

newHeaderKey :: IO AES256
newHeaderKey :: IO AES256
newHeaderKey = do
    key <- Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
keyLength :: IO ByteString
    return $ throwCryptoError $ C.cipherInit key

----------------------------------------------------------------

-- The header is encrypted so that tokens do not reveal how they relate.
addHeader :: TokenManager -> Index -> Counter -> ByteString -> IO ByteString
addHeader :: TokenManager -> Word16 -> Word64 -> ByteString -> IO ByteString
addHeader TokenManager{IO (Secret, Word16)
Word64
AES256
ThreadId
Word16 -> IO Secret
headerKey :: TokenManager -> AES256
getEncryptSecret :: TokenManager -> IO (Secret, Word16)
getDecryptSecret :: TokenManager -> Word16 -> IO Secret
threadId :: TokenManager -> ThreadId
lifetimeNSec :: TokenManager -> Word64
headerKey :: AES256
getEncryptSecret :: IO (Secret, Word16)
getDecryptSecret :: Word16 -> IO Secret
threadId :: ThreadId
lifetimeNSec :: Word64
..} Word16
idx Word64
counter ByteString
cipher = do
    hdrbin <- Header -> IO ByteString
encodeHeader (Header -> IO ByteString) -> Header -> IO ByteString
forall a b. (a -> b) -> a -> b
$ Word16 -> Word64 -> Header
Header Word16
idx Word64
counter
    let padding = Int -> Word8 -> ByteString
BS.replicate (Int
headerLength Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
hdrbin) Word8
0
        blk = AES256 -> ByteString -> ByteString
forall ba. ByteArray ba => AES256 -> ba -> ba
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
C.ecbEncrypt AES256
headerKey (ByteString
hdrbin ByteString -> ByteString -> ByteString
`BS.append` ByteString
padding)
    return (blk `BS.append` cipher)

delHeader
    :: TokenManager -> ByteString -> IO (Maybe (Index, Counter, ByteString))
delHeader :: TokenManager
-> ByteString -> IO (Maybe (Word16, Word64, ByteString))
delHeader TokenManager{IO (Secret, Word16)
Word64
AES256
ThreadId
Word16 -> IO Secret
headerKey :: TokenManager -> AES256
getEncryptSecret :: TokenManager -> IO (Secret, Word16)
getDecryptSecret :: TokenManager -> Word16 -> IO Secret
threadId :: TokenManager -> ThreadId
lifetimeNSec :: TokenManager -> Word64
headerKey :: AES256
getEncryptSecret :: IO (Secret, Word16)
getDecryptSecret :: Word16 -> IO Secret
threadId :: ThreadId
lifetimeNSec :: Word64
..} ByteString
token
    | ByteString -> Int
BS.length ByteString
token Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
headerLength = Maybe (Word16, Word64, ByteString)
-> IO (Maybe (Word16, Word64, ByteString))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Word16, Word64, ByteString)
forall a. Maybe a
Nothing
    | Bool
otherwise = do
        let (ByteString
blk, ByteString
cipher) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
headerLength ByteString
token
            (ByteString
hdrbin, ByteString
padding) =
                Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (Int
indexLength Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
counterLength) (ByteString -> (ByteString, ByteString))
-> ByteString -> (ByteString, ByteString)
forall a b. (a -> b) -> a -> b
$ AES256 -> ByteString -> ByteString
forall ba. ByteArray ba => AES256 -> ba -> ba
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
C.ecbDecrypt AES256
headerKey ByteString
blk
        if (Word8 -> Bool) -> ByteString -> Bool
BS.any (Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
0) ByteString
padding
            then Maybe (Word16, Word64, ByteString)
-> IO (Maybe (Word16, Word64, ByteString))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Word16, Word64, ByteString)
forall a. Maybe a
Nothing
            else do
                Header{..} <- ByteString -> IO Header
decodeHeader ByteString
hdrbin
                return $ Just (headerIndex, headerCounter, cipher)

-- | Encrypting a target value to get a token.
encryptToken
    :: TokenManager
    -> ByteString
    -> IO ByteString
encryptToken :: TokenManager -> ByteString -> IO ByteString
encryptToken TokenManager
mgr ByteString
x = do
    (secret, idx) <- TokenManager -> IO (Secret, Word16)
getEncryptSecret TokenManager
mgr
    now <- getMonotonicTimeNSec
    (counter, cipher) <- encrypt secret (bytestring64 now `BS.append` x)
    addHeader mgr idx counter cipher

encrypt
    :: Secret
    -> ByteString
    -> IO (Counter, ByteString)
encrypt :: Secret -> ByteString -> IO (Word64, ByteString)
encrypt Secret
secret ByteString
plain = do
    counter <- IORef Word64 -> (Word64 -> (Word64, Word64)) -> IO Word64
forall a b. IORef a -> (a -> (a, b)) -> IO b
I.atomicModifyIORef' (Secret -> IORef Word64
secretCounter Secret
secret) (\Word64
i -> (Word64
i Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
1, Word64
i))
    let nonce = Word64 -> ByteString -> ByteString
makeNonce Word64
counter (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Secret -> ByteString
secretIV Secret
secret
        cipher = ByteString -> ByteString -> ByteString -> ByteString
aes256gcmEncrypt ByteString
plain (Secret -> ByteString
secretKey Secret
secret) ByteString
nonce
    return (counter, cipher)

-- | Decrypting a token to get a target value.
decryptToken
    :: TokenManager
    -> ByteString
    -> IO (Maybe ByteString)
decryptToken :: TokenManager -> ByteString -> IO (Maybe ByteString)
decryptToken TokenManager
mgr ByteString
token = do
    mx <- TokenManager
-> ByteString -> IO (Maybe (Word16, Word64, ByteString))
delHeader TokenManager
mgr ByteString
token
    case mx of
        Maybe (Word16, Word64, ByteString)
Nothing -> Maybe ByteString -> IO (Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe ByteString
forall a. Maybe a
Nothing
        Just (Word16
idx, Word64
counter, ByteString
cipher) -> do
            secret <- TokenManager -> Word16 -> IO Secret
getDecryptSecret TokenManager
mgr Word16
idx
            mplain <- decrypt secret counter cipher
            now <- getMonotonicTimeNSec
            return $ mplain >>= checkLifetime now
  where
    checkLifetime :: Word64 -> ByteString -> Maybe ByteString
checkLifetime Word64
now ByteString
plain
        | ByteString -> Int
BS.length ByteString
plain Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
8 = Maybe ByteString
forall a. Maybe a
Nothing
        | Word64
issued Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
now Bool -> Bool -> Bool
&& Word64
now Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
issued Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= TokenManager -> Word64
lifetimeNSec TokenManager
mgr = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
x
        | Bool
otherwise = Maybe ByteString
forall a. Maybe a
Nothing
      where
        (ByteString
hdr, ByteString
x) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
8 ByteString
plain
        issued :: Word64
issued = ByteString -> Word64
word64 ByteString
hdr

decrypt
    :: Secret
    -> Counter
    -> ByteString
    -> IO (Maybe ByteString)
decrypt :: Secret -> Word64 -> ByteString -> IO (Maybe ByteString)
decrypt Secret
secret Word64
counter ByteString
cipher = do
    let nonce :: ByteString
nonce = Word64 -> ByteString -> ByteString
makeNonce Word64
counter (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Secret -> ByteString
secretIV Secret
secret
    Maybe ByteString -> IO (Maybe ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe ByteString -> IO (Maybe ByteString))
-> Maybe ByteString -> IO (Maybe ByteString)
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString -> ByteString -> Maybe ByteString
aes256gcmDecrypt ByteString
cipher (Secret -> ByteString
secretKey Secret
secret) ByteString
nonce

makeNonce :: Counter -> ByteString -> ByteString
makeNonce :: Word64 -> ByteString -> ByteString
makeNonce Word64
counter ByteString
iv = ByteString
iv ByteString -> ByteString -> ByteString
forall a b c.
(ByteArrayAccess a, ByteArrayAccess b, ByteArray c) =>
a -> b -> c
`BA.xor` ByteString
cv
  where
    cv :: ByteString
cv = Int -> Word8 -> ByteString
BS.replicate (Int
ivLength Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
counterLength) Word8
0 ByteString -> ByteString -> ByteString
`BS.append` Word64 -> ByteString
bytestring64 Word64
counter

----------------------------------------------------------------

constantAdditionalData :: ByteString
constantAdditionalData :: ByteString
constantAdditionalData = ByteString
BS.empty

aes256gcmEncrypt
    :: ByteString
    -> ByteString
    -> ByteString
    -> ByteString
aes256gcmEncrypt :: ByteString -> ByteString -> ByteString -> ByteString
aes256gcmEncrypt ByteString
plain ByteString
key ByteString
nonce = ByteString
cipher ByteString -> ByteString -> ByteString
`BS.append` (Bytes -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert Bytes
tag)
  where
    conn :: AES256
conn = CryptoFailable AES256 -> AES256
forall a. CryptoFailable a -> a
throwCryptoError (ByteString -> CryptoFailable AES256
forall key. ByteArray key => key -> CryptoFailable AES256
forall cipher key.
(Cipher cipher, ByteArray key) =>
key -> CryptoFailable cipher
C.cipherInit ByteString
key) :: AES256
    aeadIni :: AEAD AES256
aeadIni = CryptoFailable (AEAD AES256) -> AEAD AES256
forall a. CryptoFailable a -> a
throwCryptoError (CryptoFailable (AEAD AES256) -> AEAD AES256)
-> CryptoFailable (AEAD AES256) -> AEAD AES256
forall a b. (a -> b) -> a -> b
$ AEADMode -> AES256 -> ByteString -> CryptoFailable (AEAD AES256)
forall cipher iv.
(BlockCipher cipher, ByteArrayAccess iv) =>
AEADMode -> cipher -> iv -> CryptoFailable (AEAD cipher)
forall iv.
ByteArrayAccess iv =>
AEADMode -> AES256 -> iv -> CryptoFailable (AEAD AES256)
C.aeadInit AEADMode
AEAD_GCM AES256
conn ByteString
nonce
    (AuthTag Bytes
tag, ByteString
cipher) = AEAD AES256
-> ByteString -> ByteString -> Int -> (AuthTag, ByteString)
forall aad ba a.
(ByteArrayAccess aad, ByteArray ba) =>
AEAD a -> aad -> ba -> Int -> (AuthTag, ba)
C.aeadSimpleEncrypt AEAD AES256
aeadIni ByteString
constantAdditionalData ByteString
plain Int
tagLength

aes256gcmDecrypt
    :: ByteString
    -> ByteString
    -> ByteString
    -> Maybe ByteString
aes256gcmDecrypt :: ByteString -> ByteString -> ByteString -> Maybe ByteString
aes256gcmDecrypt ByteString
ctexttag ByteString
key ByteString
nonce = do
    aes <- CryptoFailable AES256 -> Maybe AES256
forall a. CryptoFailable a -> Maybe a
maybeCryptoError (CryptoFailable AES256 -> Maybe AES256)
-> CryptoFailable AES256 -> Maybe AES256
forall a b. (a -> b) -> a -> b
$ ByteString -> CryptoFailable AES256
forall key. ByteArray key => key -> CryptoFailable AES256
forall cipher key.
(Cipher cipher, ByteArray key) =>
key -> CryptoFailable cipher
C.cipherInit ByteString
key :: Maybe AES256
    aead <- maybeCryptoError $ C.aeadInit AEAD_GCM aes nonce
    let (ctext, tag) = BS.splitAt (BS.length ctexttag - tagLength) ctexttag
        authtag = Bytes -> AuthTag
AuthTag (Bytes -> AuthTag) -> Bytes -> AuthTag
forall a b. (a -> b) -> a -> b
$ ByteString -> Bytes
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert ByteString
tag
    C.aeadSimpleDecrypt aead constantAdditionalData ctext authtag