/
hashutils.py
229 lines (187 loc) · 6.51 KB
/
hashutils.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# encoding: utf-8
'''
A collection of hashing and encoding utils.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import base64
import hashlib
import hmac
import random
import os
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.platform
import salt.utils.stringutils
from salt.utils.decorators.jinja import jinja_filter
@jinja_filter('base64_encode')
def base64_b64encode(instr):
'''
Encode a string as base64 using the "modern" Python interface.
Among other possible differences, the "modern" encoder does not include
newline ('\\n') characters in the encoded output.
'''
return salt.utils.stringutils.to_unicode(
base64.b64encode(salt.utils.stringutils.to_bytes(instr)),
encoding='utf8' if salt.utils.platform.is_windows() else None
)
@jinja_filter('base64_decode')
def base64_b64decode(instr):
'''
Decode a base64-encoded string using the "modern" Python interface.
'''
decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr))
try:
return salt.utils.stringutils.to_unicode(
decoded,
encoding='utf8' if salt.utils.platform.is_windows() else None
)
except UnicodeDecodeError:
return decoded
def base64_encodestring(instr):
'''
Encode a byte-like object as base64 using the "modern" Python interface.
Among other possible differences, the "modern" encoder includes
a newline ('\\n') character after every 76 characters and always
at the end of the encoded string.
'''
# Handles PY2
if six.PY2:
return salt.utils.stringutils.to_unicode(
base64.encodestring(salt.utils.stringutils.to_bytes(instr)),
encoding='utf8' if salt.utils.platform.is_windows() else None
)
# Handles PY3
return salt.utils.stringutils.to_unicode(
base64.encodebytes(salt.utils.stringutils.to_bytes(instr)),
encoding='utf8' if salt.utils.platform.is_windows() else None
)
def base64_decodestring(instr):
'''
Decode a base64-encoded byte-like object using the "modern" Python interface.
'''
bvalue = salt.utils.stringutils.to_bytes(instr)
# Handles PY2
if six.PY2:
decoded = base64.decodestring(bvalue)
# Handles PY3
if six.PY3:
decoded = base64.decodebytes(bvalue)
try:
return salt.utils.stringutils.to_unicode(
decoded,
encoding='utf8' if salt.utils.platform.is_windows() else None
)
except UnicodeDecodeError:
return decoded
@jinja_filter('md5')
def md5_digest(instr):
'''
Generate an md5 hash of a given string.
'''
return salt.utils.stringutils.to_unicode(
hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest()
)
@jinja_filter('sha1')
def sha1_digest(instr):
'''
Generate an sha1 hash of a given string.
'''
if six.PY3:
b = salt.utils.stringutils.to_bytes(instr)
return hashlib.sha1(b).hexdigest()
return hashlib.sha1(instr).hexdigest()
@jinja_filter('sha256')
def sha256_digest(instr):
'''
Generate a sha256 hash of a given string.
'''
return salt.utils.stringutils.to_unicode(
hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest()
)
@jinja_filter('sha512')
def sha512_digest(instr):
'''
Generate a sha512 hash of a given string
'''
return salt.utils.stringutils.to_unicode(
hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest()
)
@jinja_filter('hmac')
def hmac_signature(string, shared_secret, challenge_hmac):
'''
Verify a challenging hmac signature against a string / shared-secret
Returns a boolean if the verification succeeded or failed.
'''
msg = salt.utils.stringutils.to_bytes(string)
key = salt.utils.stringutils.to_bytes(shared_secret)
challenge = salt.utils.stringutils.to_bytes(challenge_hmac)
hmac_hash = hmac.new(key, msg, hashlib.sha256)
valid_hmac = base64.b64encode(hmac_hash.digest())
return valid_hmac == challenge
@jinja_filter('hmac_compute')
def hmac_compute(string, shared_secret):
'''
Create an hmac digest.
'''
msg = salt.utils.stringutils.to_bytes(string)
key = salt.utils.stringutils.to_bytes(shared_secret)
hmac_hash = hmac.new(key, msg, hashlib.sha256).hexdigest()
return hmac_hash
@jinja_filter('random_hash')
def random_hash(size=9999999999, hash_type=None):
'''
Return a hash of a randomized data from random.SystemRandom()
'''
if not hash_type:
hash_type = 'md5'
hasher = getattr(hashlib, hash_type)
return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest()
@jinja_filter('file_hashsum')
def get_hash(path, form='sha256', chunk_size=65536):
'''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really be trusted since it is vulnerable to
collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'``
'''
hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None
if hash_type is None:
raise ValueError('Invalid hash type: {0}'.format(form))
with salt.utils.files.fopen(path, 'rb') as ifile:
hash_obj = hash_type()
# read the file in in chunks, not the entire file
for chunk in iter(lambda: ifile.read(chunk_size), b''):
hash_obj.update(chunk)
return hash_obj.hexdigest()
class DigestCollector(object):
'''
Class to collect digest of the file tree.
'''
def __init__(self, form='sha256', buff=0x10000):
'''
Constructor of the class.
:param form:
'''
self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None
if self.__digest is None:
raise ValueError('Invalid hash type: {0}'.format(form))
self.__buff = buff
def add(self, path):
'''
Update digest with the file content by path.
:param path:
:return:
'''
with salt.utils.files.fopen(path, 'rb') as ifile:
for chunk in iter(lambda: ifile.read(self.__buff), b''):
self.__digest.update(chunk)
def digest(self):
'''
Get digest.
:return:
'''
return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)