-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNOM256.py
More file actions
532 lines (396 loc) · 14.9 KB
/
NOM256.py
File metadata and controls
532 lines (396 loc) · 14.9 KB
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
#!usr/bin/env python
"""
::: NOM256 :::
A Cryptographic Hash Algorithm
- version: 2
- Source: https://github.com/torresjrjr/CryptoHashAlgorithm
---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
"""
print(__doc__)
import os
import time
from datetime import timedelta
from matplotlib import pyplot as plt
import numpy as np
import json
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Reading `settings.json` ###
with open('hash-settings.json', 'r') as f:
settingsdict = json.load(f)
print("---- SETTINGS ----\n", settingsdict, "\n---- ---- ---- ----\n")
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Functions for presentation and outputs ###
RATE = 4.2535969274764765e-05 # seconds per character.
def createHashcodeString(digest):
"""
Returns a hexadecimal hash string of alphanumeric characters,
given a digest list of integers ranging from 0 to 15.
"""
map_num2hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
hashcodelist = [None] * len(digest)
for i1 in range(0, len(digest)):
digest_i = digest[i1] # Extracts the number from the digest.
hashcodelist[i1] = map_num2hex[digest_i] # Turns the number to a hex value and assigns it to the hashcodelist.
hashcodestring = ""
for i1 in range(0, len(hashcodelist)):
hashcodestring = hashcodestring + hashcodelist[i1] # Appends the characters to form a string.
return hashcodestring
def hashcodeGrid4x4x4(hashcodestring):
"""
Prints a 4 x 4 x 4 grid of alphanumeric hexadecimal characters,
representing a 64 character hash string.
"""
hashcodegrid = [" "," "," "," "]
i1 = 0
while i1 < 64: # every character.
linenum = int(i1/16) # every 16th character.
if i1 % 4 == 3: # every 4th character.
hashcodegrid[linenum] = hashcodegrid[linenum] + hashcodestring[i1] + " "
else: # every other character.
hashcodegrid[linenum] = hashcodegrid[linenum] + hashcodestring[i1]
i1=i1+1
#print("- - - - - - - - - - -")
print("+---- ---- ---- ----+")
for line in hashcodegrid:
print(line)
print("+---- ---- ---- ----+")
#print("- - - - - - - - - - -")
def approximateTime(meal):
"""
Returns an estimated time to compute a hash of a given meal string.
The relationship is known to be linear.
"""
RATE = 4.2535969274764765e-05 # seconds per character.
time = len(meal)**1 * RATE
return time
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Functions for preparing the data ###
def prepareMealFromFile(filepath="meal.txt"):
"""
Returns a meal as a string of binary ones and zeros, from any file.
"""
print(f'Reading file: {filepath}')
if os.path.isfile(filepath):
pass
else:
print("<!> File `meal.txt` does not exist in the same directory.\n",
"To hash a file, make a copy of it in the same directory and rename it `meal.txt`.\n",
"To hash some text, create a file named `meal.txt` in the same directory.\n",
"NOM256 will create a few files, including `outhash.txt` which will include your hash.\n",
"To learn more, open the README.md file in a text editor, or go to:\n",
"< https://github.com/torresjrjr/CryptoHashAlgorithm >")
input("<.> Press ENTER to quit")
quit()
extra_raw_meal = "The quick brown fox jumps over the lazy dog." * 10
with open(filepath, 'rb') as f:
rawmeal = str(f.read())
rawmeal += extra_raw_meal
binstring = ""
for char in rawmeal:
binstring += bin(ord(char))
binstring = binstring.replace("b","10")
stringSuffix = "1011"*64 # filler string of length 256.
# Adds enough filler string to be multiple of 256:
binstring += stringSuffix[:((len(stringSuffix)-len(binstring))%len(stringSuffix))]
return binstring
def prepareMealFromString(string=""):
"""
Prepares a meal as a string, from a string input.
"""
binstring = ""
for char in string:
binstring += bin(ord(char))
binstring = binstring.replace("b","10")
stringSuffix = "10"*128 # filler string of length 256.
# Adds enough filler string to be multiple of 256:
binstring += stringSuffix[:((len(stringSuffix)-len(binstring))%len(stringSuffix))]
return binstring
def splitUpMeal(bigmeal, max_multiple=16):
"""
Returns a list of equally long partitions of a very large meal string.
Helps with frequent feedback between hashing partitions, such as
print statements of estimated time left.
"""
batch_size = 256 * max_multiple # 4096
stringSuffix = "10" * int(batch_size/2) # filler string of length 256.
# Adds enough filler string to be multiple of 256:
bigmeal += stringSuffix[:((len(stringSuffix)-len(bigmeal))%len(stringSuffix))]
batch_list = [bigmeal[i:i+batch_size] for i in range(0, len(bigmeal), batch_size)]
return batch_list
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Preparation of the data ###
print("Preparing data to hash...")
TIME_1 = time.time()
T1 = time.time()
meal = prepareMealFromFile()
#meal = prepareMealFromString('The quick brown fox jumps over the lazy dog.')
MEAL_LENGTH = len(meal)
batch_list = splitUpMeal(meal)
T2 = time.time()
TIMETAKEN = T2-T1
print("time taken:", TIMETAKEN)
print("--- --- --- \n meal preview:\n" + str(meal[:254]) + "\n...\n")
print("length of meal:", len(meal))
#print("quotient of 256:",len(meal)/256)
#print("remainder of 256:",len(meal)%256)
#print("##################################")
#print("--- --- --- \n batch_list preview:\n", batch_list[0], "\n...\n")
print("Total batches:",len(batch_list))
#print("##################################")
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Functions for creating a hash ###
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def createIts(meal):
its = [prime%(len(meal)) for prime in primes]
return its
its = [prime%(len(meal)) for prime in primes]
def nom(meal, i1):
"""
Returns a pseudorandom character derived from an input string.
"""
# Iterators
#numOfIts = len(meal)
#its = [i1 for i1 in range(0,numOfIts)]
#its = [0,2,1,6, len(meal)]
#its = createIts(meal)
numOfIts = len(its)
newnom = 0
for i2 in range(0,numOfIts):
newnom += int(meal[its[i2]+i1]) + primes[i2]
#print(primes[i2])
#print("newnom =", newnom)
newnom = str(newnom % 10)
return newnom
def nibble(meal):
"""
Returns a string made of characters returned from the nom() function,
derived from the input meal string.
"""
broth = ""
for i1 in range(-len(meal), 0):
broth += nom(meal, i1)
return broth
def munch(broth, numOfMunches):
"""
Repeats the nibble() function along a string,
to return a pseudorandom string from an input meal string.
"""
for i1 in range(numOfMunches):
broth = nibble(broth)
return broth
def chew(broth):
"""
Returns a list of pseudorandom integers ranging from 0 to 15,
of a quarter of the size of the (normally 256-long)
intermediate meal string (the broth).
"""
broth = munch(broth, 4)
#thing = broth
#print(type(thing), len(thing), len(thing)%256)
broth_list_int = []
for char in broth:
broth_list_int.append(int(char))
#thing = broth_list_int
#print(type(thing), len(thing), len(thing)%256)
digest_list_four = []
tempInt = 0
i1 = 0
for inte in broth_list_int:
if i1 % 4 != 0:
tempInt += inte
tempInt = tempInt % 16
else:
digest_list_four.append(tempInt)
tempInt = 0
i1 += 1
thing = digest_list_four
#print(type(thing), len(thing), len(thing)%64)
return digest_list_four
def gulp(meal):
"""
Return a list of pseudorandom integers ranging from 0 to 15,
compiled from multiple runs of the chew() function, after
dividing a long meal string into equal parts (normally 256).
"""
#print("Proccessing...")
broth = meal
chunks = [broth[i:i+256] for i in range(0, len(broth), 256)]
#print("Number of chunks:", len(chunks))
#print(" - Chunkified...")
digest = [0]*64
i1 = 1
global Ti
Ti = 0
for chunk in chunks:
t1 = time.time()
if i1 == 1:
chewed = chew(chunk)
digest = chewed
else:
chewed = chew(chunk)
digest = [(int(x) + int(y))%16 for x, y in zip(digest, chewed)]
t2 = time.time()
#print("time taken:", t2-t1)
Ti += t2-t1
#print("time TOTAL:", Ti)
#print(" - Chewed!")
i1 += 1
#print("Hash finished.")
return digest
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Creating a hash ###
#print(meal)
print("##########################################################################")
print("Hashing...")
T1 = time.time()
#broth = gulp(meal)
i2 = 0
broth_batch_list = []
for meal in batch_list:
broth_batch_list += [gulp(meal)]
#print("broth_batch_list:\n", broth_batch_list)
i2 += 1
Total_batches_left = len(batch_list) - i2
batch_size = len(batch_list[0])
seconds_left = Total_batches_left * RATE * batch_size
print("Total batches left: "+str(Total_batches_left)+
" Estimated Time: "+str(timedelta(seconds=seconds_left)))
print("broth_batch_list length:", len(broth_batch_list))
broth = [((sum(x) + max(x)) % 16) for x in zip(*broth_batch_list)]
T2 = time.time()
TIME_2 = time.time()
print("##########################################################################")
#print("DIGEST:\n", broth)
TIMETAKEN = T2 - T1
TIMETAKEN = TIME_2 - TIME_1
print("time taken:", TIMETAKEN)
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Finalising a hash ###
broth_list_int = []
for char in broth:
broth_list_int.append(int(char))
tempInt = 0
for inte in broth_list_int:
tempInt = (tempInt + inte) % 16
broth_list_int[0] = tempInt
#print("broth_list_int: \n", broth_list_int)
thing = broth_list_int
#print(type(thing), len(thing), len(thing)%64)
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Calculating stats for presenting a hash ###
broth_list_int_sorted = sorted(broth_list_int)
#print(broth_list_int_sorted)
thing = broth_list_int_sorted
#print(type(thing), len(thing), len(thing)%64)
average_value = sum(broth_list_int)/len(broth_list_int)
#average_value = 7.5
#print("average_value =", average_value)
def sigmoid01(x, xmid, L, k):
"""
A mathematical sigmoid function, the 'Logistic function'.
A reference: < https://en.wikipedia.org/wiki/Logistic_function >.
"""
euler = 2.71828182845904523536028747135266249775724709369995
sigma = L/(1 + euler**(-k*(x-xmid)))
return sigma
# temp.
average_value_adj = (average_value+0.5)
#print("average_value_adj =", average_value_adj)
sigmoid_value = sigmoid01(average_value_adj, 8, 16, 4)
#print("sigmoid_value =", sigmoid_value)
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Presenting a hash ###
HashcodeString = createHashcodeString(broth_list_int)
x = broth_list_int
fig = plt.figure(
num=None,
figsize=(10, 5),
dpi=128,
facecolor='w',
edgecolor='b',
)
ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
hint_max = 0.3
hint = sigmoid01(average_value_adj, 8, hint_max*2, 4) - hint_max
#print(hint)
#faceColor = (max(0, hint), 0, max(0, -hint))
faceColor = (max(0, hint), max(0, (hint_max-abs(hint)) ), max(0, -hint))
#faceColor = (max(0, hint), max(0, (hint_max-abs(hint))**2), max(0, -hint))
#print(faceColor)
#ax.set_facecolor('#FFFFFF')
#ax.set_facecolor('#0c1111')
ax.set_facecolor(faceColor)
plt.xticks(np.arange(0, 256+1, 4.0))
plt.yticks(np.arange(0, 15+1, 2.0))
plt.grid(b=True, which='major', axis='both', linestyle=':', color='#555555')
plt.grid(b=True, which='minor', axis='both', linestyle='-', color='g')
plt.plot(broth_list_int, 'wo:')
#plt.plot(broth_list_int, 'ko:')
plt.plot(broth_list_int_sorted, 'r.-')
plt.title(HashcodeString, {'fontsize': 16}, fontfamily='consolas')
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Saving the hash-graph ###
outhash_image_path = 'outhash.png'
print(f"`{outhash_image_path}` will be saved once figure is closed")
plt.show()
print(f"Saving hash output graph `{outhash_image_path}`...")
fig.savefig(outhash_image_path, dpi=fig.dpi);
print(f"`{outhash_image_path}` saved")
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Printing the hash ###
print("\nOutput hash:")
HashcodeString = createHashcodeString(broth_list_int)
print(HashcodeString)
print("\n4x4x4 hash grid.:")
hashcodeGrid4x4x4(HashcodeString)
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Verifying hash output validity ###
def verifyHashcode(digest):
"""
Verifies the hash as a NOM256 Hash.
"""
list_str = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
list_num = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 ]
total = 0
for i2 in range(len(digest)):
digest_i = digest[i2]
#print("digest_i =", digest_i)
for i1 in range(16):
if digest_i == list_str[i1] and i2 != 0:
total += list_num[i1]
#print("total =", total)
#print("list_num[i1] =", list_num[i1])
continue
#print("--- --- ---")
#print("total =", total)
checknum = total % 16
#print("checknum =", checknum)
checkstr = list_str[checknum]
#print("checkstr =", checkstr)
checkorg = digest[0]
#print("checkorg =", checkorg)
if checkorg == checkstr:
isValid = True
else:
isValid = False
return isValid
print("\nVerifying hash validity...")
print("Validity is", str(verifyHashcode(HashcodeString)))
print("\n")
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### Writing the hash output ###
with open('outhash.txt', 'w') as f:
f.write(HashcodeString)
print('\'outhash.txt\' saved and ready.')
with open('outhash-history.txt', 'a') as f:
f.write(HashcodeString + "\n")
print('\'outhash-history.txt\' saved and ready.')
with open('outhash-testing.txt', 'a') as f:
f.write(HashcodeString + " {'meal_length':"+str(MEAL_LENGTH)+", 'time_taken':"+str(TIMETAKEN)+"}\n")
print('\'outhash-testing.txt\' saved and ready.')
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
### END ###
DONE_TIMER = 5
print(f'Done. Quitting in {DONE_TIMER} seconds')
time.sleep(DONE_TIMER)
print("END")