{-# LANGUAGE OverloadedStrings #-}
-- | Authenticated encryption using Skein for PRNG, KDF, stream cipher and MAC.
module Crypto.Threefish.Authenticated (
    DecryptFailure (..), Encrypted, Plaintext, Block256, Nonce256, Key256,
    encrypt, decrypt, encrypt', decrypt', encryptBytes, decryptBytes,
    generateNonce, toBlock, fromBlock
  ) where
import Crypto.Threefish
import Crypto.Threefish.Threefish256 (Block256(..))
import Crypto.Threefish.Skein
import Crypto.Threefish.Skein.KDF hiding (deriveKeys)
import qualified Crypto.Threefish.Skein.StreamCipher as SC
import Crypto.Threefish.Random
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import System.IO.Unsafe
import Data.IORef
import Data.Serialize
import Control.Monad

{-# NOINLINE prng #-}
prng :: IORef SkeinGen
prng :: IORef SkeinGen
prng = IO (IORef SkeinGen) -> IORef SkeinGen
forall a. IO a -> a
unsafePerformIO (IO (IORef SkeinGen) -> IORef SkeinGen)
-> IO (IORef SkeinGen) -> IORef SkeinGen
forall a b. (a -> b) -> a -> b
$ IO SkeinGen
newSkeinGen IO SkeinGen
-> (SkeinGen -> IO (IORef SkeinGen)) -> IO (IORef SkeinGen)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= SkeinGen -> IO (IORef SkeinGen)
forall a. a -> IO (IORef a)
newIORef

-- | Strict version of 'atomicModifyIORef'.  This forces both the value stored
-- in the 'IORef' as well as the value returned.
atomicModIORef' :: IORef a -> (a -> (a,b)) -> IO b
atomicModIORef' :: forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModIORef' IORef a
ref a -> (a, b)
f = do
    b
b <- IORef a -> (a -> (a, b)) -> IO b
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef IORef a
ref
            (\a
x -> let (a
a, b
b) = a -> (a, b)
f a
x
                    in (a
a, a
a a -> b -> b
forall a b. a -> b -> b
`seq` b
b))
    b
b b -> IO b -> IO b
forall a b. a -> b -> b
`seq` b -> IO b
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return b
b

-- | Generate a 256 bit nonce using the Skein PRNG.
generateNonce :: IO Nonce256
generateNonce :: IO Nonce256
generateNonce =
    ByteString -> Nonce256
Block256 (ByteString -> Nonce256) -> IO ByteString -> IO Nonce256
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` IORef SkeinGen
-> (SkeinGen -> (SkeinGen, ByteString)) -> IO ByteString
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModIORef' IORef SkeinGen
prng ((ByteString, SkeinGen) -> (SkeinGen, ByteString)
forall {b} {a}. (b, a) -> (a, b)
pflip ((ByteString, SkeinGen) -> (SkeinGen, ByteString))
-> (SkeinGen -> (ByteString, SkeinGen))
-> SkeinGen
-> (SkeinGen, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> SkeinGen -> (ByteString, SkeinGen)
randomBytes Int
32)
  where
    pflip :: (b, a) -> (a, b)
pflip (b
a, a
b) = (a
b, b
a)

type MAC256 = Block256
type Plaintext = BSL.ByteString

data DecryptFailure = BadMAC | NoDecode String deriving Int -> DecryptFailure -> ShowS
[DecryptFailure] -> ShowS
DecryptFailure -> String
(Int -> DecryptFailure -> ShowS)
-> (DecryptFailure -> String)
-> ([DecryptFailure] -> ShowS)
-> Show DecryptFailure
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DecryptFailure -> ShowS
showsPrec :: Int -> DecryptFailure -> ShowS
$cshow :: DecryptFailure -> String
show :: DecryptFailure -> String
$cshowList :: [DecryptFailure] -> ShowS
showList :: [DecryptFailure] -> ShowS
Show

-- | An encrypt-then-MACed value. The binary format is as follows:
--   Bytes    What
--   0-31     256 bit nonce
--   32-63    256 bit Skein-MAC
--   64-71    Length of cryptotext as a 64 bit little endian word.
--   71-      Cryptotext
data Encrypted a = Encrypted {
    forall a. Encrypted a -> Nonce256
encNonce :: Nonce256, 
    forall a. Encrypted a -> Nonce256
encMAC   :: MAC256, 
    forall a. Encrypted a -> ByteString
encData  :: BSL.ByteString
  } deriving Int -> Encrypted a -> ShowS
[Encrypted a] -> ShowS
Encrypted a -> String
(Int -> Encrypted a -> ShowS)
-> (Encrypted a -> String)
-> ([Encrypted a] -> ShowS)
-> Show (Encrypted a)
forall a. Int -> Encrypted a -> ShowS
forall a. [Encrypted a] -> ShowS
forall a. Encrypted a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall a. Int -> Encrypted a -> ShowS
showsPrec :: Int -> Encrypted a -> ShowS
$cshow :: forall a. Encrypted a -> String
show :: Encrypted a -> String
$cshowList :: forall a. [Encrypted a] -> ShowS
showList :: [Encrypted a] -> ShowS
Show

instance Serialize (Encrypted a) where
  put :: Putter (Encrypted a)
put (Encrypted (Block256 ByteString
nonce) (Block256 ByteString
mac) ByteString
cryptotext) = do
    Putter ByteString
putByteString ByteString
nonce
    Putter ByteString
putByteString ByteString
mac
    Putter Word64
putWord64le (Int64 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int64 -> Word64) -> Int64 -> Word64
forall a b. (a -> b) -> a -> b
$ ByteString -> Int64
BSL.length ByteString
cryptotext)
    Putter ByteString
putLazyByteString ByteString
cryptotext
  get :: Get (Encrypted a)
get = do
    ByteString
nonce <- Int -> Get ByteString
getByteString Int
32
    ByteString
mac <- Int -> Get ByteString
getByteString Int
32
    Word64
len <- Get Word64
getWord64le
    ByteString
cryptotext <- Int64 -> Get ByteString
getLazyByteString (Word64 -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
len)
    Encrypted a -> Get (Encrypted a)
forall a. a -> Get a
forall (m :: * -> *) a. Monad m => a -> m a
return (Encrypted a -> Get (Encrypted a))
-> Encrypted a -> Get (Encrypted a)
forall a b. (a -> b) -> a -> b
$! Nonce256 -> Nonce256 -> ByteString -> Encrypted a
forall a. Nonce256 -> Nonce256 -> ByteString -> Encrypted a
Encrypted (ByteString -> Nonce256
Block256 ByteString
nonce) (ByteString -> Nonce256
Block256 ByteString
mac) ByteString
cryptotext

deriveKeys :: Key256 -> (Key256, Key256)
deriveKeys :: Nonce256 -> (Nonce256, Nonce256)
deriveKeys Nonce256
k = (Nonce256 -> Nonce256 -> Nonce256
deriveKey Nonce256
k (ByteString -> Nonce256
Block256 (ByteString -> Nonce256) -> ByteString -> Nonce256
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString -> ByteString
BS.append ByteString
"crypt" (Int -> Word8 -> ByteString
BS.replicate Int
27 Word8
0)),
                Nonce256 -> Nonce256 -> Nonce256
deriveKey Nonce256
k (ByteString -> Nonce256
Block256 (ByteString -> Nonce256) -> ByteString -> Nonce256
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString -> ByteString
BS.append ByteString
"mac" (Int -> Word8 -> ByteString
BS.replicate Int
29 Word8
0)))

-- | Encrypt-then-MAC a message given a key and a nonce. Note that using the
--   same nonce more than once for a given key will completely destroy
--   security.
encrypt' :: Key256 -> Nonce256 -> Plaintext -> Encrypted a
encrypt' :: forall a. Nonce256 -> Nonce256 -> ByteString -> Encrypted a
encrypt' Nonce256
k Nonce256
n ByteString
plaintext =
    Nonce256 -> Nonce256 -> ByteString -> Encrypted a
forall a. Nonce256 -> Nonce256 -> ByteString -> Encrypted a
Encrypted Nonce256
n Nonce256
mac ByteString
cryptotext
  where
    (Nonce256
cryptKey, Nonce256
macKey) = Nonce256 -> (Nonce256, Nonce256)
deriveKeys Nonce256
k
    cryptotext :: ByteString
cryptotext = Nonce256 -> Nonce256 -> ByteString -> ByteString
SC.encrypt Nonce256
cryptKey Nonce256
n ByteString
plaintext
    mac :: Nonce256
mac = Nonce256 -> ByteString -> Nonce256
forall a. Skein a => a -> ByteString -> a
skeinMAC Nonce256
macKey ByteString
cryptotext

-- | Verify and decrypt a message.
decrypt' :: Key256 -> Encrypted a -> Either DecryptFailure Plaintext
decrypt' :: forall a.
Nonce256 -> Encrypted a -> Either DecryptFailure ByteString
decrypt' Nonce256
k (Encrypted Nonce256
n Nonce256
mac ByteString
cryptotext) = do
    Bool -> Either DecryptFailure () -> Either DecryptFailure ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Nonce256
mac' Nonce256 -> Nonce256 -> Bool
forall a. Eq a => a -> a -> Bool
/= Nonce256
mac) (Either DecryptFailure () -> Either DecryptFailure ())
-> Either DecryptFailure () -> Either DecryptFailure ()
forall a b. (a -> b) -> a -> b
$ DecryptFailure -> Either DecryptFailure ()
forall a b. a -> Either a b
Left DecryptFailure
BadMAC
    ByteString -> Either DecryptFailure ByteString
forall a. a -> Either DecryptFailure a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> Either DecryptFailure ByteString)
-> ByteString -> Either DecryptFailure ByteString
forall a b. (a -> b) -> a -> b
$! Nonce256 -> Nonce256 -> ByteString -> ByteString
SC.decrypt Nonce256
cryptKey Nonce256
n ByteString
cryptotext
  where
    (Nonce256
cryptKey, Nonce256
macKey) = Nonce256 -> (Nonce256, Nonce256)
deriveKeys Nonce256
k
    mac' :: Nonce256
mac' = Nonce256 -> ByteString -> Nonce256
forall a. Skein a => a -> ByteString -> a
skeinMAC Nonce256
macKey ByteString
cryptotext

-- | Encrypt-then-MAC any serializable value.
--   The 256 bit nonce is generated using a Skein-based PRNG seeded from the
--   system's entropy pool. This means that two successive calls to encrypt
--   will not yield the exact same output; however, the identity
--   forall k, x. Right x == decrypt k (encrypt k x)
--   will always hold.
--
--   The subkeys for encryption and MAC are generated by applying Skein-KDF
--   to the master key, with the key identifiers "crypt" and "mac"
--   respectively, zero padded at the end until 32 bytes.
encrypt :: Serialize a => Key256 -> a -> Encrypted a
encrypt :: forall a. Serialize a => Nonce256 -> a -> Encrypted a
encrypt Nonce256
k a
x =  IO (Encrypted a) -> Encrypted a
forall a. IO a -> a
unsafePerformIO (IO (Encrypted a) -> Encrypted a)
-> IO (Encrypted a) -> Encrypted a
forall a b. (a -> b) -> a -> b
$ do
  Nonce256
nonce <- IO Nonce256
generateNonce
  Encrypted a -> IO (Encrypted a)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Encrypted a -> IO (Encrypted a))
-> Encrypted a -> IO (Encrypted a)
forall a b. (a -> b) -> a -> b
$! Nonce256 -> Nonce256 -> ByteString -> Encrypted a
forall a. Nonce256 -> Nonce256 -> ByteString -> Encrypted a
encrypt' Nonce256
k Nonce256
nonce (Put -> ByteString
runPutLazy (Putter a
forall t. Serialize t => Putter t
put a
x))

-- | Encrypt-then-MAC a lazy ByteString.
encryptBytes :: Key256 -> BSL.ByteString -> BSL.ByteString
encryptBytes :: Nonce256 -> ByteString -> ByteString
encryptBytes Nonce256
k ByteString
bs = IO ByteString -> ByteString
forall a. IO a -> a
unsafePerformIO (IO ByteString -> ByteString) -> IO ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ do
  Nonce256
nonce <- IO Nonce256
generateNonce
  ByteString -> IO ByteString
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> IO ByteString) -> ByteString -> IO ByteString
forall a b. (a -> b) -> a -> b
$! Put -> ByteString
runPutLazy (Put -> ByteString) -> Put -> ByteString
forall a b. (a -> b) -> a -> b
$! Putter (Encrypted Any)
forall t. Serialize t => Putter t
put (Nonce256 -> Nonce256 -> ByteString -> Encrypted Any
forall a. Nonce256 -> Nonce256 -> ByteString -> Encrypted a
encrypt' Nonce256
k Nonce256
nonce ByteString
bs)

-- | Decrypt and decode a message. Will fail if there is a MAC mismatch or if
--   the message can't be decoded into the given data type.
decrypt :: Serialize a => Key256 -> Encrypted a -> Either DecryptFailure a
decrypt :: forall a.
Serialize a =>
Nonce256 -> Encrypted a -> Either DecryptFailure a
decrypt Nonce256
k Encrypted a
enc = do
  ByteString
plaintext <- Nonce256 -> Encrypted a -> Either DecryptFailure ByteString
forall a.
Nonce256 -> Encrypted a -> Either DecryptFailure ByteString
decrypt' Nonce256
k Encrypted a
enc
  case Get a -> ByteString -> Either String a
forall a. Get a -> ByteString -> Either String a
runGetLazy Get a
forall t. Serialize t => Get t
get ByteString
plaintext of
    Right a
x  -> a -> Either DecryptFailure a
forall a. a -> Either DecryptFailure a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x
    Left String
err -> DecryptFailure -> Either DecryptFailure a
forall a b. a -> Either a b
Left (String -> DecryptFailure
NoDecode String
err)

-- | Verify and decrypt a lazy ByteString.
decryptBytes :: Key256 -> BSL.ByteString -> Either DecryptFailure Plaintext
decryptBytes :: Nonce256 -> ByteString -> Either DecryptFailure ByteString
decryptBytes Nonce256
k ByteString
bs = do
  Encrypted Any
enc <- case Get (Encrypted Any) -> ByteString -> Either String (Encrypted Any)
forall a. Get a -> ByteString -> Either String a
runGetLazy Get (Encrypted Any)
forall t. Serialize t => Get t
get ByteString
bs of
           Right Encrypted Any
x  -> Encrypted Any -> Either DecryptFailure (Encrypted Any)
forall a. a -> Either DecryptFailure a
forall (m :: * -> *) a. Monad m => a -> m a
return Encrypted Any
x
           Left String
err -> DecryptFailure -> Either DecryptFailure (Encrypted Any)
forall a b. a -> Either a b
Left (String -> DecryptFailure
NoDecode String
err)
  Nonce256 -> Encrypted Any -> Either DecryptFailure ByteString
forall a.
Nonce256 -> Encrypted a -> Either DecryptFailure ByteString
decrypt' Nonce256
k Encrypted Any
enc