summaryrefslogtreecommitdiffhomepage
path: root/ExpensiveHash.hs
blob: ca357bca38525092b882e32753a72eadebc9a4ae (plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
{-# LANGUAGE OverloadedStrings #-}

module ExpensiveHash where

import Types
import Cost
import Tunables
import qualified Data.ByteString as B
import Raaz.Core.Encode
import qualified Crypto.Argon2 as Argon2
import Data.Time.Clock
import Control.DeepSeq

-- | A hash that is expensive to calculate.
--
-- This is a lynchpin of keysafe's security, because using this hash
-- as an encryption key forces brute force attackers to generate
-- hashes over and over again, taking a very long time.
data ExpensiveHash = ExpensiveHash (Cost CreationOp) B.ByteString
	deriving (Show)

data Salt t = Salt t

expensiveHash :: Encodable t => Tunables -> Salt t -> Password -> ExpensiveHash
expensiveHash tunables (Salt s) (Password password) = 
	ExpensiveHash (argonCost tunables) $
		Argon2.hash (argonOptions tunables) password (toByteString s)

benchmarkExpensiveHash :: Tunables -> IO (Benchmark (Cost CreationOp))
benchmarkExpensiveHash tunables = do
	start <- getCurrentTime
	let ExpensiveHash expected b = expensiveHash tunables
		(Salt (KeyIdent gpgKey (Name ("benchmark" :: B.ByteString))))
		(Password ("himom" :: B.ByteString))
	end <- b `deepseq` getCurrentTime
	let diff = floor $ end `diffUTCTime` start
	let actual = CPUCost $ Seconds diff
	return $ Benchmark
		{ expectedBenchmark = expected
		, actualBenchmark = actual
		}