4 # Copyright (C) 2006, 2007, 2010, 2011 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 """Utility functions for hashing.
28 from ganeti import compat
31 def Sha1Hmac(key, text, salt=None):
32 """Calculates the HMAC-SHA1 digest of a text.
34 HMAC is defined in RFC2104.
37 @param key: Secret key
42 salted_text = salt + text
46 return hmac.new(key, salted_text, compat.sha1).hexdigest()
49 def VerifySha1Hmac(key, text, digest, salt=None):
50 """Verifies the HMAC-SHA1 digest of a text.
52 HMAC is defined in RFC2104.
55 @param key: Secret key
58 @param digest: Expected digest
60 @return: Whether HMAC-SHA1 digest matches
63 return digest.lower() == Sha1Hmac(key, text, salt=salt).lower()
66 def _FingerprintFile(filename):
67 """Compute the fingerprint of a file.
69 If the file does not exist, a None will be returned
73 @param filename: the filename to checksum
75 @return: the hex digest of the sha checksum of the contents
79 if not (os.path.exists(filename) and os.path.isfile(filename)):
84 fp = compat.sha1_hash()
95 def FingerprintFiles(files):
96 """Compute fingerprints for a list of files.
99 @param files: the list of filename to fingerprint
101 @return: a dictionary filename: fingerprint, holding only
107 for filename in files:
108 cksum = _FingerprintFile(filename)
110 ret[filename] = cksum