Add LV parser
[ganeti-local] / src / Ganeti / Hash.hs
1 {-| Crypto-related helper functions.
2
3 -}
4
5 {-
6
7 Copyright (C) 2011, 2012 Google Inc.
8
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.
13
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.
18
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
22 02110-1301, USA.
23
24 -}
25
26 module Ganeti.Hash
27   ( computeMac
28   , verifyMac
29   , HashKey
30   ) where
31
32 import qualified Data.ByteString as B
33 import Data.Char
34 import Data.HMAC (hmac_sha1)
35 import qualified Data.Text as T
36 import Data.Text.Encoding (encodeUtf8)
37 import Data.Word
38 import Text.Printf (printf)
39
40 -- | Type alias for the hash key. This depends on the library being
41 -- used.
42 type HashKey = [Word8]
43
44 -- | Converts a string to a list of bytes.
45 stringToWord8 :: String -> HashKey
46 stringToWord8 = B.unpack . encodeUtf8 . T.pack
47
48 -- | Converts a list of bytes to a string.
49 word8ToString :: HashKey -> String
50 word8ToString = concatMap (printf "%02x")
51
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
56
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