-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Manual_implementation_of_some_hash_functions.py
1651 lines (1139 loc) · 65 KB
/
Manual_implementation_of_some_hash_functions.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
# # Table of Contents
# <p><div class="lev1 toc-item"><a href="#Manual-implementation-of-some-hash-functions" data-toc-modified-id="Manual-implementation-of-some-hash-functions-1"><span class="toc-item-num">1 </span>Manual implementation of some hash functions</a></div><div class="lev2 toc-item"><a href="#What-is-a-hash-function?" data-toc-modified-id="What-is-a-hash-function?-11"><span class="toc-item-num">1.1 </span>What is a hash function?</a></div><div class="lev2 toc-item"><a href="#Common-API-for-the-different-classes" data-toc-modified-id="Common-API-for-the-different-classes-12"><span class="toc-item-num">1.2 </span>Common API for the different classes</a></div><div class="lev2 toc-item"><a href="#Checking-the-the-hashlib-module-in-Python-standard-library" data-toc-modified-id="Checking-the-the-hashlib-module-in-Python-standard-library-13"><span class="toc-item-num">1.3 </span>Checking the <a href="https://docs.python.org/3/library/hashlib.html" target="_blank">the <code>hashlib</code> module in Python standard library</a></a></div><div class="lev2 toc-item"><a href="#First-stupid-example:-a-stupid-hashing-function" data-toc-modified-id="First-stupid-example:-a-stupid-hashing-function-14"><span class="toc-item-num">1.4 </span>First stupid example: a stupid hashing function</a></div><div class="lev2 toc-item"><a href="#First-real-example:-the-MD5-hashing-function" data-toc-modified-id="First-real-example:-the-MD5-hashing-function-15"><span class="toc-item-num">1.5 </span>First real example: the MD5 hashing function</a></div><div class="lev3 toc-item"><a href="#Useful-functions-for-the-MD5-algorithm" data-toc-modified-id="Useful-functions-for-the-MD5-algorithm-151"><span class="toc-item-num">1.5.1 </span>Useful functions for the MD5 algorithm</a></div><div class="lev3 toc-item"><a href="#The-MD5-class" data-toc-modified-id="The-MD5-class-152"><span class="toc-item-num">1.5.2 </span>The <code>MD5</code> class</a></div><div class="lev3 toc-item"><a href="#First-check-on-MD5" data-toc-modified-id="First-check-on-MD5-153"><span class="toc-item-num">1.5.3 </span>First check on MD5</a></div><div class="lev3 toc-item"><a href="#A-less-stupid-check-on-MD5" data-toc-modified-id="A-less-stupid-check-on-MD5-154"><span class="toc-item-num">1.5.4 </span>A less stupid check on MD5</a></div><div class="lev3 toc-item"><a href="#Trying-1000-random-examples" data-toc-modified-id="Trying-1000-random-examples-155"><span class="toc-item-num">1.5.5 </span>Trying 1000 random examples</a></div><div class="lev2 toc-item"><a href="#Second-real-example:-the-SHA-1-hashing-function" data-toc-modified-id="Second-real-example:-the-SHA-1-hashing-function-16"><span class="toc-item-num">1.6 </span>Second real example: the SHA-1 hashing function</a></div><div class="lev3 toc-item"><a href="#Useful-functions-the-SHA-1-algorithm" data-toc-modified-id="Useful-functions-the-SHA-1-algorithm-161"><span class="toc-item-num">1.6.1 </span>Useful functions the SHA-1 algorithm</a></div><div class="lev3 toc-item"><a href="#The-SHA1-class" data-toc-modified-id="The-SHA1-class-162"><span class="toc-item-num">1.6.2 </span>The <code>SHA1</code> class</a></div><div class="lev3 toc-item"><a href="#First-check-on-SHA-1" data-toc-modified-id="First-check-on-SHA-1-163"><span class="toc-item-num">1.6.3 </span>First check on SHA-1</a></div><div class="lev3 toc-item"><a href="#A-less-stupid-check-on-SHA-1" data-toc-modified-id="A-less-stupid-check-on-SHA-1-164"><span class="toc-item-num">1.6.4 </span>A less stupid check on SHA-1</a></div><div class="lev3 toc-item"><a href="#Trying-1000-random-examples" data-toc-modified-id="Trying-1000-random-examples-165"><span class="toc-item-num">1.6.5 </span>Trying 1000 random examples</a></div><div class="lev2 toc-item"><a href="#Third-real-example:-the-SHA-2-hashing-function" data-toc-modified-id="Third-real-example:-the-SHA-2-hashing-function-17"><span class="toc-item-num">1.7 </span>Third real example: the SHA-2 hashing function</a></div><div class="lev3 toc-item"><a href="#Useful-functions-the-SHA-2-algorithm" data-toc-modified-id="Useful-functions-the-SHA-2-algorithm-171"><span class="toc-item-num">1.7.1 </span>Useful functions the SHA-2 algorithm</a></div><div class="lev3 toc-item"><a href="#The-SHA2-class" data-toc-modified-id="The-SHA2-class-172"><span class="toc-item-num">1.7.2 </span>The <code>SHA2</code> class</a></div><div class="lev3 toc-item"><a href="#First-check-on-SHA-2" data-toc-modified-id="First-check-on-SHA-2-173"><span class="toc-item-num">1.7.3 </span>First check on SHA-2</a></div><div class="lev3 toc-item"><a href="#Check-on-SHA-2" data-toc-modified-id="Check-on-SHA-2-174"><span class="toc-item-num">1.7.4 </span>Check on SHA-2</a></div><div class="lev3 toc-item"><a href="#Trying-1000-random-examples" data-toc-modified-id="Trying-1000-random-examples-175"><span class="toc-item-num">1.7.5 </span>Trying 1000 random examples</a></div><div class="lev2 toc-item"><a href="#Comparison-:-MD5-vs-SHA-1-vs-SHA-2" data-toc-modified-id="Comparison-:-MD5-vs-SHA-1-vs-SHA-2-18"><span class="toc-item-num">1.8 </span>Comparison : MD5 vs SHA-1 vs SHA-2</a></div><div class="lev2 toc-item"><a href="#Bonus-:-SHA-2-variants" data-toc-modified-id="Bonus-:-SHA-2-variants-19"><span class="toc-item-num">1.9 </span>Bonus : SHA-2 variants</a></div><div class="lev3 toc-item"><a href="#SHA-224" data-toc-modified-id="SHA-224-191"><span class="toc-item-num">1.9.1 </span>SHA-224</a></div><div class="lev4 toc-item"><a href="#The-SHA224-class" data-toc-modified-id="The-SHA224-class-1911"><span class="toc-item-num">1.9.1.1 </span>The <code>SHA224</code> class</a></div><div class="lev4 toc-item"><a href="#Checks-on-SHA-224" data-toc-modified-id="Checks-on-SHA-224-1912"><span class="toc-item-num">1.9.1.2 </span>Checks on SHA-224</a></div><div class="lev3 toc-item"><a href="#SHA-512" data-toc-modified-id="SHA-512-192"><span class="toc-item-num">1.9.2 </span>SHA-512</a></div><div class="lev4 toc-item"><a href="#Useful-functions-the-SHA-512-algorithm" data-toc-modified-id="Useful-functions-the-SHA-512-algorithm-1921"><span class="toc-item-num">1.9.2.1 </span>Useful functions the SHA-512 algorithm</a></div><div class="lev4 toc-item"><a href="#The-SHA512-class" data-toc-modified-id="The-SHA512-class-1922"><span class="toc-item-num">1.9.2.2 </span>The <code>SHA512</code> class</a></div><div class="lev4 toc-item"><a href="#Checks-on-SHA-512" data-toc-modified-id="Checks-on-SHA-512-1923"><span class="toc-item-num">1.9.2.3 </span>Checks on SHA-512</a></div><div class="lev3 toc-item"><a href="#SHA-384" data-toc-modified-id="SHA-384-193"><span class="toc-item-num">1.9.3 </span>SHA-384</a></div><div class="lev4 toc-item"><a href="#The-SHA384-class" data-toc-modified-id="The-SHA384-class-1931"><span class="toc-item-num">1.9.3.1 </span>The <code>SHA384</code> class</a></div><div class="lev4 toc-item"><a href="#Checks-on-SHA-384" data-toc-modified-id="Checks-on-SHA-384-1932"><span class="toc-item-num">1.9.3.2 </span>Checks on SHA-384</a></div><div class="lev3 toc-item"><a href="#More-comparison" data-toc-modified-id="More-comparison-194"><span class="toc-item-num">1.9.4 </span>More comparison</a></div><div class="lev2 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-110"><span class="toc-item-num">1.10 </span>Conclusion</a></div><div class="lev3 toc-item"><a href="#Bonus" data-toc-modified-id="Bonus-1101"><span class="toc-item-num">1.10.1 </span>Bonus</a></div>
# # Manual implementation of some hash functions
#
# This small [Jupyter notebook](https://www.Jupyter.org/) is a short experiment, to see if I can implement the some basic [Hashing functions](https://en.wikipedia.org/wiki/Hash_function), more specifically [cryptographic hashing functions](https://en.wikipedia.org/wiki/Cryptographic_hash_function), like `MD5`, `SHA1`, `SHA256`, `SHA512` etc
#
# And then I want compare my manual implementations with the functions implemented in [the `hashlib` module in Python standard library](https://docs.python.org/3/library/hashlib.html).
# Ideally, my implementation should work exactly like the reference one, only slower!
#
#
# - *Reference*: Wikipedia pages on [Hash functions](https://en.wikipedia.org/wiki/Hash_function), [MD5](https://en.wikipedia.org/wiki/MD5), [SHA-1](https://en.wikipedia.org/wiki/SHA1) and [SHA-2](https://en.wikipedia.org/wiki/SHA-2), as well as [the `hashlib` module in Python standard library](https://docs.python.org/3/library/hashlib.html).
# - *Date*: 13 May 2017 (first part about MD5), 19 June 2017 (second part about SHA-1), 19 June 2017 (last part about SHA-2).
# - *Author*: [Lilian Besson](https://GitHub.com/Naereen/notebooks).
# - *License*: [MIT Licensed](https://LBesson.MIT-License.org/).
# ----
# ## What is a hash function?
# > TL;DR : [Hash functions](https://en.wikipedia.org/wiki/Hash_function) and [cryptographic hashing functions](https://en.wikipedia.org/wiki/Cryptographic_hash_function) on Wikipedia.
# ----
# ## Common API for the different classes
#
# I will copy the API proposed by [the `hashlib` module in Python standard library](https://docs.python.org/3/library/hashlib.html), so it will be very easy to compare my implementations with the one provided with your default [Python](https://www.Python.org/) installation.
# In[1]:
class Hash(object):
""" Common class for all hash methods.
It copies the one of the hashlib module (https://docs.python.org/3.5/library/hashlib.html).
"""
def __init__(self, *args, **kwargs):
""" Create the Hash object."""
self.name = self.__class__.__name__ # https://docs.python.org/3.5/library/hashlib.html#hashlib.hash.name
self.byteorder = 'little'
self.digest_size = 0 # https://docs.python.org/3.5/library/hashlib.html#hashlib.hash.digest_size
self.block_size = 0 # https://docs.python.org/3.5/library/hashlib.html#hashlib.hash.block_size
def __str__(self):
return self.name
def update(self, arg):
""" Update the hash object with the object arg, which must be interpretable as a buffer of bytes."""
pass
def digest(self):
""" Return the digest of the data passed to the update() method so far. This is a bytes object of size digest_size which may contain bytes in the whole range from 0 to 255."""
return b""
def hexdigest(self):
""" Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments."""
digest = self.digest()
raw = digest.to_bytes(self.digest_size, byteorder=self.byteorder)
format_str = '{:0' + str(2 * self.digest_size) + 'x}'
return format_str.format(int.from_bytes(raw, byteorder='big'))
# ----
# ## Checking the [the `hashlib` module in Python standard library](https://docs.python.org/3/library/hashlib.html)
# In[2]:
import hashlib
# We can check [the available algorithms](https://docs.python.org/3.5/library/hashlib.html#hashlib.algorithms_available), some of them being [guaranteed to be on any platform](https://docs.python.org/3.5/library/hashlib.html#hashlib.algorithms_guaranteed), some are not.
# In[3]:
list(hashlib.algorithms_available)
# I will need at least these ones:
# In[4]:
assert 'MD5' in hashlib.algorithms_available
assert 'SHA1' in hashlib.algorithms_available
assert 'SHA256' in hashlib.algorithms_available
assert 'SHA224' in hashlib.algorithms_available
assert 'SHA512' in hashlib.algorithms_available
assert 'SHA384' in hashlib.algorithms_available
# Lets check that they have the block size and digest size announced:
# In[5]:
for name, s in zip(
('MD5', 'SHA1', 'SHA256', 'SHA224', 'SHA512', 'SHA384'),
(hashlib.md5(), hashlib.sha1(), hashlib.sha256(), hashlib.sha224(), hashlib.sha512(), hashlib.sha384())
):
print("For {:<8} : the block size is {:<3} and the digest size is {:<2}.".format(name, s.block_size, s.digest_size))
# ----
# ## First stupid example: a stupid hashing function
#
# This "stupid" hashing function will use `digest_size` of 128 bytes (= 16 bits), and compute it by ... just looking at the first 128 bytes of the input data.
#
# This is just to check the API and how to read from a bytes buffer.
# In[6]:
class HeaderHash(Hash):
""" This "stupid" hashing function will use `digest_size` of 128 bytes, and compute it by ... just looking at the first 128 bytes of the input data.
"""
def __init__(self):
# Common part
self.digest_size = 16
self.block_size = 16
self.name = "Header"
# Specific part
self._data = b""
def update(self, arg):
""" Update the hash object with the object arg, which must be interpretable as a buffer of bytes."""
if len(self._data) == 0:
self._data = arg[:self.block_size]
def digest(self):
""" Return the digest of the data passed to the update() method so far. This is a bytes object of size digest_size which may contain bytes in the whole range from 0 to 255."""
return self._data
# Let us try it:
# In[7]:
h1 = HeaderHash()
# In[8]:
h1
print(h1)
# Let us use some toy data, to test here and after.
# In[9]:
data = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" * 100
# In[10]:
h1.update(data)
h1.digest()
# > Well... It seems to work, even if this first example is stupid.
# ----
# ## First real example: the MD5 hashing function
# Let start with a simple one: [the MD5 hashing function](https://en.wikipedia.org/wiki/MD5), from Rivest in 1992.
#
# <center><span style="font-size: large; color: red;"><b>Warning</b>: it is considered broken since at least 2012, never use it for security purposes.</span></center>
# ### Useful functions for the MD5 algorithm
# Instead of writing the complete MD5 algorithm in the class below, I preferred to define here some useful functions, using [Bitwise operators](https://wiki.python.org/moin/BitwiseOperators).
# In[11]:
def MD5_f1(b, c, d):
""" First ternary bitwise operation."""
return ((b & c) | ((~b) & d)) & 0xFFFFFFFF
def MD5_f2(b, c, d):
""" Second ternary bitwise operation."""
return ((b & d) | (c & (~d))) & 0xFFFFFFFF
def MD5_f3(b, c, d):
""" Third ternary bitwise operation."""
return (b ^ c ^ d) & 0xFFFFFFFF
def MD5_f4(b, c, d):
""" Forth ternary bitwise operation."""
return (c ^ (b | (~d))) & 0xFFFFFFFF
# In[12]:
def leftrotate(x, c):
""" Left rotate the number x by c bytes."""
x &= 0xFFFFFFFF
return ((x << c) | (x >> (32 - c))) & 0xFFFFFFFF
# In[13]:
def leftshift(x, c):
""" Left shift the number x by c bytes."""
return x << c
# In[14]:
from math import floor, sin
# ### The `MD5` class
# It is a direct implementation of the pseudo-code, as given for instance on the Wikipedia page, or the original research article by Rivest.
# In[15]:
class MD5(Hash):
"""MD5 hashing, see https://en.wikipedia.org/wiki/MD5#Algorithm."""
def __init__(self):
self.name = "MD5"
self.byteorder = 'little'
self.block_size = 64
self.digest_size = 16
# Internal data
s = [0] * 64
K = [0] * 64
# Initialize s, s specifies the per-round shift amounts
s[ 0:16] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22]
s[16:32] = [5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20]
s[32:48] = [4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23]
s[48:64] = [6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
# Store it
self._s = s
# Use binary integer part of the sines of integers (Radians) as constants:
for i in range(64):
K[i] = floor(2**32 * abs(sin(i + 1))) & 0xFFFFFFFF
# Store it
self._K = K
# Initialize variables:
a0 = 0x67452301 # A
b0 = 0xefcdab89 # B
c0 = 0x98badcfe # C
d0 = 0x10325476 # D
self.hash_pieces = [a0, b0, c0, d0]
def update(self, arg):
s, K = self._s, self._K
a0, b0, c0, d0 = self.hash_pieces
# 1. Pre-processing
data = bytearray(arg)
orig_len_in_bits = (8 * len(data)) & 0xFFFFFFFFFFFFFFFF
# 1.a. Add a single '1' bit at the end of the input bits
data.append(0x80)
# 1.b. Padding with zeros as long as the input bits length ≡ 448 (mod 512)
while len(data) % 64 != 56:
data.append(0)
# 1.c. append original length in bits mod (2 pow 64) to message
data += orig_len_in_bits.to_bytes(8, byteorder='little')
assert len(data) % 64 == 0, "Error in padding"
# 2. Computations
# Process the message in successive 512-bit = 64-bytes chunks:
for offset in range(0, len(data), 64):
# 2.a. 512-bits = 64-bytes chunks
chunks = data[offset : offset + 64]
# 2.b. Break chunk into sixteen 32-bit = 4-bytes words M[j], 0 ≤ j ≤ 15
A, B, C, D = a0, b0, c0, d0
# 2.c. Main loop
for i in range(64):
if 0 <= i <= 15:
F = MD5_f1(B, C, D)
g = i
elif 16 <= i <= 31:
F = MD5_f2(B, C, D)
g = (5 * i + 1) % 16
elif 32 <= i <= 47:
F = MD5_f3(B, C, D)
g = (3 * i + 5) % 16
elif 48 <= i <= 63:
F = MD5_f4(B, C, D)
g = (7 * i) % 16
# Be wary of the below definitions of A, B, C, D
to_rotate = (A + F + K[i] + int.from_bytes(chunks[4*g : 4*g+4], byteorder='little')) & 0xFFFFFFFF
new_B = (B + leftrotate(to_rotate, s[i])) & 0xFFFFFFFF
A, B, C, D = D, new_B, B, C
# Add this chunk's hash to result so far:
a0 = (a0 + A) & 0xFFFFFFFF
b0 = (b0 + B) & 0xFFFFFFFF
c0 = (c0 + C) & 0xFFFFFFFF
d0 = (d0 + D) & 0xFFFFFFFF
# 3. Conclusion
self.hash_pieces = [a0, b0, c0, d0]
def digest(self):
return sum(leftshift(x, (32 * i)) for i, x in enumerate(self.hash_pieces))
# We can also write a function to directly compute the hex digest from some bytes data.
# In[16]:
def hash_MD5(data):
""" Shortcut function to directly receive the hex digest from MD5(data)."""
h = MD5()
if isinstance(data, str):
data = bytes(data, encoding='utf8')
h.update(data)
return h.hexdigest()
# <div style="text-align:right;"><blockquote> *Note:* [This page helped for debugging](https://rosettacode.org/wiki/MD5/Implementation#Python).</blockquote></div>
# ### First check on MD5
#
# Let us try it:
# In[17]:
h2 = MD5()
h2
print(h2)
# In[18]:
h2.update(data)
h2.digest()
# In[19]:
h2.hexdigest()
# ### A less stupid check on MD5
#
# Let try the example from [MD5 Wikipedia page](https://en.wikipedia.org/wiki/MD5#MD5_hashes) :
# In[20]:
hash_MD5("The quick brown fox jumps over the lazy dog")
assert hash_MD5("The quick brown fox jumps over the lazy dog") == '9e107d9d372bb6826bd81d3542a419d6'
# Even a small change in the message will (with overwhelming probability) result in a mostly different hash, due to the [**avalanche effect**](https://en.wikipedia.org/wiki/Avalanche_effect). For example, adding a period to the end of the sentence:
# In[21]:
hash_MD5("The quick brown fox jumps over the lazy dog.")
assert hash_MD5("The quick brown fox jumps over the lazy dog.") == 'e4d909c290d0fb1ca068ffaddf22cbd0'
# The hash of the zero-length string is:
# In[22]:
hash_MD5("")
assert hash_MD5("") == 'd41d8cd98f00b204e9800998ecf8427e'
# $\implies$ We obtained the same result, OK our function works!
# ### Trying 1000 random examples
# On a small sentence:
# In[23]:
hash_MD5("My name is Zorro !")
# In[24]:
h = hashlib.md5()
h.update(b"My name is Zorro !")
h.hexdigest()
# It starts to look good.
# In[25]:
def true_hash_MD5(data):
h = hashlib.md5()
if isinstance(data, str):
data = bytes(data, encoding='utf8')
h.update(data)
return h.hexdigest()
# On some random data:
# In[26]:
import numpy.random as nr
alphabets = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def random_string(size=10000):
return ''.join(alphabets[nr.randint(len(alphabets))] for _ in range(size))
# In[27]:
random_string(10)
# In[28]:
from tqdm import tqdm_notebook as tqdm
# In[29]:
get_ipython().run_cell_magic('time', '', 'for _ in tqdm(range(1000)):\n x = random_string()\n assert hash_MD5(x) == true_hash_MD5(x), "Error: x = {} gave two different MD5 hashes: my implementation = {} != hashlib implementation = {}...".format(x, hash_MD5(x), true_hash_MD5(x))')
# ----
# ## Second real example: the SHA-1 hashing function
# Let now study and implement another hashing function, slightly harder to write but more secure: SHA1, "Secure Hash Algorithm, version 1".
# See [the SHA1 hashing function](https://en.wikipedia.org/wiki/SHA-1) on Wikipedia, if needed.
#
# <center><span style="font-size: large; color: red;"><b>Warning</b>: it is considered broken since at least 2011, it is not advised to use it for real security purposes. SHA-2 or SHA-3 is better advised.</span></center>
#
# For instance, see [this nice blog post](https://konklone.com/post/why-google-is-hurrying-the-web-to-kill-sha-1).
# ### Useful functions the SHA-1 algorithm
# Pretty similar to the ones used for the MD5 algorithm.
# In[30]:
def SHA1_f1(b, c, d):
""" First ternary bitwise operation."""
return ((b & c) | ((~b) & d)) & 0xFFFFFFFF
def SHA1_f2(b, c, d):
""" Second ternary bitwise operation."""
return (b ^ c ^ d) & 0xFFFFFFFF
def SHA1_f3(b, c, d):
""" Third ternary bitwise operation."""
return ((b & c) | (b & d) | (c & d) ) & 0xFFFFFFFF
def SHA1_f4(b, c, d):
""" Forth ternary bitwise operation, = SHA1_f1."""
return (b ^ c ^ d) & 0xFFFFFFFF
# This is exactly like for MD5.
# In[31]:
def leftrotate(x, c):
""" Left rotate the number x by c bytes."""
x &= 0xFFFFFFFF
return ((x << c) | (x >> (32 - c))) & 0xFFFFFFFF
# As SHA-1 plays with big-endian and little-endian integers, and at the end it requires a leftshift to combine the 5 hash pieces into one.
# In[32]:
def leftshift(x, c):
""" Left shift the number x by c bytes."""
return x << c
# ### The `SHA1` class
#
# I will use a simple class, very similar to the class used for the MD5 algorithm (see above).
# It is a direct implementation of the pseudo-code, as given for instance on the Wikipedia page.
# In[33]:
class SHA1(Hash):
"""SHA1 hashing, see https://en.wikipedia.org/wiki/SHA-1#Algorithm."""
def __init__(self):
self.name = "SHA1"
self.byteorder = 'big'
self.block_size = 64
self.digest_size = 20
# Initialize variables
h0 = 0x67452301
h1 = 0xEFCDAB89
h2 = 0x98BADCFE
h3 = 0x10325476
h4 = 0xC3D2E1F0
# Store them
self.hash_pieces = [h0, h1, h2, h3, h4]
def update(self, arg):
h0, h1, h2, h3, h4 = self.hash_pieces
# 1. Pre-processing, exactly like MD5
data = bytearray(arg)
orig_len_in_bits = (8 * len(data)) & 0xFFFFFFFFFFFFFFFF
# 1.a. Add a single '1' bit at the end of the input bits
data.append(0x80)
# 1.b. Padding with zeros as long as the input bits length ≡ 448 (mod 512)
while len(data) % 64 != 56:
data.append(0)
# 1.c. append original length in bits mod (2 pow 64) to message
data += orig_len_in_bits.to_bytes(8, byteorder='big')
assert len(data) % 64 == 0, "Error in padding"
# 2. Computations
# Process the message in successive 512-bit = 64-bytes chunks:
for offset in range(0, len(data), 64):
# 2.a. 512-bits = 64-bytes chunks
chunks = data[offset : offset + 64]
w = [0 for i in range(80)]
# 2.b. Break chunk into sixteen 32-bit = 4-bytes words w[i], 0 ≤ i ≤ 15
for i in range(16):
w[i] = int.from_bytes(chunks[4*i : 4*i + 4], byteorder='big')
# 2.c. Extend the sixteen 32-bit words into eighty 32-bit words
for i in range(16, 80):
w[i] = leftrotate(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1)
# 2.d. Initialize hash value for this chunk
a, b, c, d, e = h0, h1, h2, h3, h4
# 2.e. Main loop, cf. http://www.faqs.org/rfcs/rfc3174.html
for i in range(80):
if 0 <= i <= 19 :
f = SHA1_f1(b, c, d)
k = 0x5A827999
elif 20 <= i <= 39 :
f = SHA1_f2(b, c, d)
k = 0x6ED9EBA1
elif 40 <= i <= 59 :
f = SHA1_f3(b, c, d)
k = 0x8F1BBCDC
elif 60 <= i <= 79 :
f = SHA1_f4(b, c, d)
k = 0xCA62C1D6
new_a = leftrotate(a, 5) + f + e + k + w[i] & 0xFFFFFFFF
new_c = leftrotate(b, 30)
# Rotate the 5 variables
a, b, c, d, e = new_a, a, new_c, c, d
# Add this chunk's hash to result so far:
h0 = (h0 + a) & 0xFFFFFFFF
h1 = (h1 + b) & 0xFFFFFFFF
h2 = (h2 + c) & 0xFFFFFFFF
h3 = (h3 + d) & 0xFFFFFFFF
h4 = (h4 + e) & 0xFFFFFFFF
# 3. Conclusion
self.hash_pieces = [h0, h1, h2, h3, h4]
def digest(self):
return sum(leftshift(x, 32 * i) for i, x in enumerate(self.hash_pieces[::-1]))
# We can also write a function to directly compute the hex digest from some bytes data.
# In[34]:
def hash_SHA1(data):
""" Shortcut function to directly receive the hex digest from SHA1(data)."""
h = SHA1()
if isinstance(data, str):
data = bytes(data, encoding='utf8')
h.update(data)
return h.hexdigest()
# ### First check on SHA-1
#
# Let us try it:
# In[35]:
h3 = SHA1()
h3
print(h3)
# In[36]:
h3.update(data)
h3.digest()
# In[37]:
digest = h3.digest()
bin(digest)
len(bin(digest))
# In[38]:
h3.hexdigest()
# ### A less stupid check on SHA-1
#
# Let try the example from [SHA-1 Wikipedia page](https://en.wikipedia.org/wiki/SHA-1#SHA-1_hashes) :
# In[39]:
hash_SHA1("The quick brown fox jumps over the lazy dog")
assert hash_SHA1("The quick brown fox jumps over the lazy dog") == '2fd4e1c67a2d28fced849ee1bb76e7391b93eb12'
# Even a small change in the message will (with overwhelming probability) result in a mostly different hash, due to the [**avalanche effect**](https://en.wikipedia.org/wiki/Avalanche_effect). For example, changing one letter in the sentence:
# In[40]:
hash_SHA1("The quick brown fox jumps over the lazy cog")
assert hash_SHA1("The quick brown fox jumps over the lazy cog") == 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3'
# The hash of the zero-length string is:
# In[41]:
hash_SHA1("")
assert hash_SHA1("") == 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
# $\implies$ We obtained the same result, OK our function works!
# ### Trying 1000 random examples
# On a small sentence:
# In[42]:
hash_SHA1("My name is Zorro !")
# In[43]:
h = hashlib.sha1()
h.update(b"My name is Zorro !")
h.hexdigest()
# It starts to look good.
# In[44]:
def true_hash_SHA1(data):
h = hashlib.sha1()
if isinstance(data, str):
data = bytes(data, encoding='utf8')
h.update(data)
return h.hexdigest()
# On some random data:
# In[45]:
random_string(10)
# In[46]:
from tqdm import tqdm_notebook as tqdm
# In[47]:
get_ipython().run_cell_magic('time', '', 'for _ in tqdm(range(1000)):\n x = random_string()\n assert hash_SHA1(x) == true_hash_SHA1(x), "Error: x = {} gave two different SHA1 hashes: my implementation = {} != hashlib implementation = {}...".format(x, hash_SHA1(x), true_hash_SHA1(x))')
# ----
# ## Third real example: the SHA-2 hashing function
# Let now study and implement a last hashing function, again slightly harder to write but more secure: SHA-2, "Secure Hash Algorithm, version 2".
# See [the SHA-2 hashing function](https://en.wikipedia.org/wiki/SHA-2) on Wikipedia, if needed.
#
# <center><span style="font-size: large; color: green;"><i>Remark</i>: it is not (yet) considered broken, and it is the military standard for security and cryptographic hashing. SHA-3 is preferred for security purposes.</span></center>
# ### Useful functions the SHA-2 algorithm
# This is exactly like for MD5. But SHA-2 requires right-rotate as well.
# In[48]:
def leftrotate(x, c):
""" Left rotate the number x by c bytes."""
x &= 0xFFFFFFFF
return ((x << c) | (x >> (32 - c))) & 0xFFFFFFFF
def rightrotate(x, c):
""" Right rotate the number x by c bytes."""
x &= 0xFFFFFFFF
return ((x >> c) | (x << (32 - c))) & 0xFFFFFFFF
# As SHA-2 plays with big-endian and little-endian integers, and at the end it requires a leftshift to combine the 5 hash pieces into one.
# In[49]:
def leftshift(x, c):
""" Left shift the number x by c bytes."""
return x << c
def rightshift(x, c):
""" Right shift the number x by c bytes."""
return x >> c
# ### The `SHA2` class
#
# I will use a simple class, very similar to the class used for the SHA-1 algorithm (see above).
# It is a direct implementation of the pseudo-code, as given for instance on the Wikipedia page.
#
# I will only implement the simpler one, SHA-256, of digest size of 256 bits. Other variants are SHA-224, SHA-384, SHA-512 (and others include SHA-512/224, SHA-512/256).
# In[50]:
class SHA2(Hash):
"""SHA256 hashing, see https://en.wikipedia.org/wiki/SHA-2#Pseudocode."""
def __init__(self):
self.name = "SHA256"
self.byteorder = 'big'
self.block_size = 64
self.digest_size = 32
# Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63
# Note 3: The compression function uses 8 working variables, a through h
# Note 4: Big-endian convention is used when expressing the constants in this pseudocode,
# and when parsing message block data from bytes to words, for example,
# the first word of the input message "abc" after padding is 0x61626380
# Initialize hash values:
# (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h0 = 0x6a09e667
h1 = 0xbb67ae85
h2 = 0x3c6ef372
h3 = 0xa54ff53a
h4 = 0x510e527f
h5 = 0x9b05688c
h6 = 0x1f83d9ab
h7 = 0x5be0cd19
# Initialize array of round constants:
# (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):
self.k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
# Store them
self.hash_pieces = [h0, h1, h2, h3, h4, h5, h6, h7]
def update(self, arg):
h0, h1, h2, h3, h4, h5, h6, h7 = self.hash_pieces
# 1. Pre-processing, exactly like MD5
data = bytearray(arg)
orig_len_in_bits = (8 * len(data)) & 0xFFFFFFFFFFFFFFFF
# 1.a. Add a single '1' bit at the end of the input bits
data.append(0x80)
# 1.b. Padding with zeros as long as the input bits length ≡ 448 (mod 512)
while len(data) % 64 != 56:
data.append(0)
# 1.c. append original length in bits mod (2 pow 64) to message
data += orig_len_in_bits.to_bytes(8, byteorder='big')
assert len(data) % 64 == 0, "Error in padding"
# 2. Computations
# Process the message in successive 512-bit = 64-bytes chunks:
for offset in range(0, len(data), 64):
# 2.a. 512-bits = 64-bytes chunks
chunks = data[offset : offset + 64]
w = [0 for i in range(64)]
# 2.b. Break chunk into sixteen 32-bit = 4-bytes words w[i], 0 ≤ i ≤ 15
for i in range(16):
w[i] = int.from_bytes(chunks[4*i : 4*i + 4], byteorder='big')
# 2.c. Extend the first 16 words into the remaining 48
# words w[16..63] of the message schedule array:
for i in range(16, 64):
s0 = (rightrotate(w[i-15], 7) ^ rightrotate(w[i-15], 18) ^ rightshift(w[i-15], 3)) & 0xFFFFFFFF
s1 = (rightrotate(w[i-2], 17) ^ rightrotate(w[i-2], 19) ^ rightshift(w[i-2], 10)) & 0xFFFFFFFF
w[i] = (w[i-16] + s0 + w[i-7] + s1) & 0xFFFFFFFF
# 2.d. Initialize hash value for this chunk
a, b, c, d, e, f, g, h = h0, h1, h2, h3, h4, h5, h6, h7
# 2.e. Main loop, cf. https://tools.ietf.org/html/rfc6234
for i in range(64):
S1 = (rightrotate(e, 6) ^ rightrotate(e, 11) ^ rightrotate(e, 25)) & 0xFFFFFFFF
ch = ((e & f) ^ ((~e) & g)) & 0xFFFFFFFF
temp1 = (h + S1 + ch + self.k[i] + w[i]) & 0xFFFFFFFF
S0 = (rightrotate(a, 2) ^ rightrotate(a, 13) ^ rightrotate(a, 22)) & 0xFFFFFFFF
maj = ((a & b) ^ (a & c) ^ (b & c)) & 0xFFFFFFFF
temp2 = (S0 + maj) & 0xFFFFFFFF
new_a = (temp1 + temp2) & 0xFFFFFFFF
new_e = (d + temp1) & 0xFFFFFFFF
# Rotate the 8 variables
a, b, c, d, e, f, g, h = new_a, a, b, c, new_e, e, f, g
# Add this chunk's hash to result so far:
h0 = (h0 + a) & 0xFFFFFFFF
h1 = (h1 + b) & 0xFFFFFFFF
h2 = (h2 + c) & 0xFFFFFFFF
h3 = (h3 + d) & 0xFFFFFFFF
h4 = (h4 + e) & 0xFFFFFFFF
h5 = (h5 + f) & 0xFFFFFFFF
h6 = (h6 + g) & 0xFFFFFFFF
h7 = (h7 + h) & 0xFFFFFFFF
# 3. Conclusion
self.hash_pieces = [h0, h1, h2, h3, h4, h5, h6, h7]
def digest(self):
# h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7
return sum(leftshift(x, 32 * i) for i, x in enumerate(self.hash_pieces[::-1]))
# We can also write a function to directly compute the hex digest from some bytes data.
# In[51]:
def hash_SHA2(data):
""" Shortcut function to directly receive the hex digest from SHA2(data)."""
h = SHA2()
if isinstance(data, str):
data = bytes(data, encoding='utf8')
h.update(data)
return h.hexdigest()
# ### First check on SHA-2
#
# Let us try it:
# In[52]:
h4 = SHA2()
h4
print(h4)
# In[53]:
h4.update(data)
h4.digest()
# In[54]:
digest = h4.digest()
bin(digest)
len(bin(digest))
# In[55]:
h4.hexdigest()
# ### Check on SHA-2
#
# Let try the example from [SHA-2 Wikipedia page](https://en.wikipedia.org/wiki/SHA-2#Test_vectors) :
# In[56]:
hash_SHA2("The quick brown fox jumps over the lazy dog")
assert hash_SHA2("The quick brown fox jumps over the lazy dog") == 'd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592'
# Even a small change in the message will (with overwhelming probability) result in a mostly different hash, due to the [**avalanche effect**](https://en.wikipedia.org/wiki/Avalanche_effect). For example, adding a period at the end of the sentence:
# In[57]:
hash_SHA2("The quick brown fox jumps over the lazy dog.")
assert hash_SHA2("The quick brown fox jumps over the lazy dog.") == 'ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c'
# The hash of the zero-length string is:
# In[58]:
hash_SHA2("")
assert hash_SHA2("") == 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
# $\implies$ We obtained the same result, OK our function works!
# ### Trying 1000 random examples
# On a small sentence:
# In[59]:
hash_SHA2("My name is Zorro !")
# In[60]:
h = hashlib.sha256()
h.update(b"My name is Zorro !")
h.hexdigest()
# It starts to look good.
# In[61]:
def true_hash_SHA2(data):
h = hashlib.sha256()
if isinstance(data, str):
data = bytes(data, encoding='utf8')
h.update(data)
return h.hexdigest()
# On some random data:
# In[62]:
random_string(10)
# In[63]:
from tqdm import tqdm_notebook as tqdm
# In[64]:
get_ipython().run_cell_magic('time', '', 'for _ in tqdm(range(1000)):\n x = random_string()\n assert hash_SHA2(x) == true_hash_SHA2(x), "Error: x = {} gave two different SHA2 hashes: my implementation = {} != hashlib implementation = {}...".format(x, hash_SHA2(x), true_hash_SHA2(x))')
# ----
# ## Comparison : MD5 vs SHA-1 vs SHA-2
#
# It can be interesting to compare each hash functions, with respect to its time complexity.
# In[65]:
def test_MD5():
x = random_string()
return hash_MD5(x) == true_hash_MD5(x)