1 {-| Crypto-related helper functions.
7 Copyright (C) 2011, 2012 Google Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
32 import qualified Data.ByteString as B
34 import Data.HMAC (hmac_sha1)
35 import qualified Data.Text as T
36 import Data.Text.Encoding (encodeUtf8)
38 import Text.Printf (printf)
40 -- | Type alias for the hash key. This depends on the library being
42 type HashKey = [Word8]
44 -- | Converts a string to a list of bytes.
45 stringToWord8 :: String -> HashKey
46 stringToWord8 = B.unpack . encodeUtf8 . T.pack
48 -- | Converts a list of bytes to a string.
49 word8ToString :: HashKey -> String
50 word8ToString = concatMap (printf "%02x")
52 -- | Computes the HMAC for a given key/test and salt.
53 computeMac :: HashKey -> Maybe String -> String -> String
54 computeMac key salt text =
55 word8ToString . hmac_sha1 key . stringToWord8 $ maybe text (++ text) salt
57 -- | Verifies the HMAC for a given message.
58 verifyMac :: HashKey -> Maybe String -> String -> String -> Bool
59 verifyMac key salt text digest =
60 map toLower digest == computeMac key salt text