• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# perceive is better than RSA

lignite Aug 14th, 2017 (edited) 168 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. """
2. Perceive Cryptography Algorythm In Python 2.7
3. Perform a series of Diffie-Hellman exchanges to
4. perceive a common data point without communicating it
5. then use this data point as the modulo for encryption
6. """
7. import hashlib
8. import random
9. from binascii import hexlify # For debug output
10. import json
11. import sys
12.
13. # If a secure random number generator is unavailable, exit with an error.
14. try:
15.     import ssl
16.     random_function = ssl.RAND_bytes
17.     random_provider = "Python SSL"
18. except (AttributeError, ImportError):
19.     import OpenSSL
20.     random_function = OpenSSL.rand.bytes
21.     random_provider = "OpenSSL"
22.
23. def xor(data, key):
24.     return bytearray(a^b for a, b in zip(*map(bytearray, [data, key])))
25.
26. def quad(a, x, b, c):
27.     blocksize = x.bit_length() // 8 + 1
28.     blocks = [a[i:i+blocksize] for i in range(0, len(a), blocksize)]
29.     y = bytearray()
30.     catalyst = pow(x, b, c)
31.     for i in range(len(blocks)):
32.         catalyst = pow(catalyst, b, c)
33. #        print("{} : {}".format(i, catalyst))
34.         y += xor(blocks[i], to_bytes(catalyst, blocksize, byteorder="big"))
35.     return y
36.
37. def to_bytes(n, length=32, byteorder="big"):
38.     h = '%x' %n
39.     s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
40.     return s if byteorder =='big' else s[::-1]
41.
42. class DiffieHellman(object):
43.     """
44.   A reference implementation of the Diffie-Hellman protocol.
45.   By default, this class uses 1536-bit MODP Group From RFC3526.
46.   """
47.
48.     def __init__(self, privateKey=None, keyLength=2048):
49.         """
50.       Generate the public and private keys.
51.       """
52.         min_keyLength        = 180
53.         self.diffie_base     = 2 # base g from Diffie's protocol
54.         self.starter_base    = 5
55.         self.starter_prime   = 101
56.         self.__fingerprint   = None
57.         self.__secret        = random.randint(500,sys.maxint)
58.         self.__g_po          = None
59.         self.__g_pO          = None
60.         self.__g_Po          = None
61.         self.__ephemeralKey  = None
62.         self.__initiator     = True
63.         self.publicKey       = None
64.
65.         if(keyLength < min_keyLength):
66.             print("Error: keyLength is too small. Setting to minimum.")
67.             self.keyLength = min_keyLength
68.         else:
69.             self.keyLength = keyLength
70.
71.         # RFC3526 1536-bit MODP Group
72.         self.prime = int('0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC7'
73.                          '4020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437'
74.                          '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDE'
75.                          'E386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598'
77.                          '529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF', 16)
78.
79.         if privateKey is None:
80.             self.privateKey = self.genPrivateKey(keyLength)
81.         else:
82.             self.privateKey = privateKey
83.         self.publicKey = self.genPublicKey() # regenerate this after establishBase()
84.
85.     def establishBase(self, challenge=None):
86.         if challenge is None:
87.             return pow(self.starter_base, self.__secret, self.starter_prime)
88.         else:
89.             self.diffie_base = pow(challenge, self.__secret, self.starter_prime)
90.             self.genPublicKey() # regenerate public key after changing base
91.
92.     def genPrivateKey(self, bits):
93.         """
94.       Generate a private key using a secure random number generator.
95.       """
96.         return self.genRandom(bits)
97.
98.     def genPublicKey(self):
99.         """
100.       Generate a public key X with g**x % p.
101.       """
102.         return pow(self.diffie_base, self.privateKey, self.prime)
103.
104.     def genRandom(self, bits):
105.         """
106.       Generate a random number with the specified number of bits
107.       """
108.         _rand = 0
109.         _bytes = bits // 8 + 8
110.
111.         while(_rand.bit_length() < bits):
112.             try:
113.                 # Python 3
114.                 _rand = int.from_bytes(random_function(_bytes), byteorder='big')
115.             except:
116.                 # Python 2
117.                 _rand = int(OpenSSL.rand.bytes(_bytes).encode('hex'), 16)
118.
119.         return _rand
120.
121.     def genKey(self, otherKey):
122.         """
123.       Derive the shared secret, then hash it to obtain the shared key.
124.       """
125.         self.sharedSecret = self.genSecret(self.privateKey, otherKey)
126.
127.         # Convert the shared secret (int) to an array of bytes in network order
128.         # Otherwise hashlib can't hash it.
129.         try:
130.             _sharedSecretBytes = self.sharedSecret.to_bytes(self.sharedSecret.bit_length() // 8 + 1, byteorder="big")
131.         except AttributeError:
132.             _sharedSecretBytes = str(self.sharedSecret)
133.
134.         s = hashlib.sha256()
135.         s.update(bytes(_sharedSecretBytes))
136.         self.key = s.digest()
137.
138.     def checkPublicKey(self, otherKey):
139.         """
140.       Check the other party's public key to make sure it's valid.
141.       Since a safe prime is used, verify that the Legendre symbol == 1
142.       """
143.         if(otherKey > 2 and otherKey < self.prime - 1):
144.             if(pow(otherKey, (self.prime - 1)//2, self.prime) == 1):
145.                 return True
146.         return False
147.
148.     def genSecret(self, privateKey, otherKey):
149.         """
150.       Check to make sure the public key is valid, then combine it with the
151.       private key to generate a shared secret.
152.       """
153.         if(self.checkPublicKey(otherKey) == True):
154.             sharedSecret = pow(otherKey, privateKey, self.prime)
155.             return sharedSecret
156.         else:
157.             raise Exception("Invalid public key.")
158.
159.     def showParams(self):
160.         """
161.       Show the parameters of the Diffie Hellman agreement.
162.       """
163.         print("Parameters:")
164.         print("Prime[{0}]: {1}".format(self.prime.bit_length(), self.prime))
165.         print("Private key[{0}]: {1}\n".format(self.privateKey.bit_length(), self.privateKey))
166.         print("Public key[{0}]: {1}".format(self.publicKey.bit_length(), self.publicKey))
167.
168.     def showResults(self):
169.         """
170.       Show the results of a Diffie-Hellman exchange.
171.       """
172.         print("Results:")
173.         print("Shared secret[{0}]: {1}".format(self.sharedSecret.bit_length(), self.sharedSecret))
174.         print("Shared key[{0}]: {1}".format(len(self.key), hexlify(self.key)))
175.
176.     def getKey(self):
177.         """
178.       Return the shared secret key
179.       """
180.         return self.key
181.
182.     def get_fingerprint(self):
183.         if self.__fingerprint:
184.             return self.__fingerprint
185.
186.         publicKey = self.publicKey
187.         return self.__make_fingerprint(publicKey)
188.
189.     def __make_fingerprint(self, pub_key):
190.         self.__fingerprint = self.__hash(pub_key)
191.         return self.__fingerprint
192.
193.     def __hash(self, *values):
194.         """Hashes the concatenation of values
195.       each element in values must be of type int
196.       """
197.         s = hashlib.sha256()
198.         for value in values:
199.             try:
200.                 value_bytes = to_bytes(value, value.bit_length() // 8 + 1, byteorder="big")
201.             except AttributeError:
202.                 value_bytes = str(value)
203.
204.             s.update(bytes(value_bytes))
205.         return s.digest()
206.
207.     def establishAccord(self, party_ephemeral, party_signature=None):
208.         if party_signature is not None:
209.            self.handshake(party_ephemeral, party_signature)
210.
211.     def getEphemeralPublicKey(self):
212.         return self.__ephemeralKey.publicKey
213.
214.     def establishEphemeralListener(self):
215.         self.__ephemeralKey = DiffieHellman()
216.         self.__initiator = False
217.
218.     def handshake(self, party_ephemeral, party_signature):
219.         if self.__initiator:
220.             self.__ephemeralKey = DiffieHellman()
221.         fingerprint = self.__make_fingerprint(party_signature)
222.         self.__ephemeralKey.genKey(party_ephemeral)
223.         self.__g_po = self.__ephemeralKey.getSecret()
224.         self.__ephemeralKey.genKey(party_signature)
225.         self.__g_pO = self.__ephemeralKey.getSecret()
226.
227.         self.genKey(party_ephemeral)
228.         self.__g_Po = self.getSecret()
229.
230.         self.__make_secret()
231.
232.     def getSecret(self):
233.         """
234.       Return the preHashed key
235.       """
236.         return self.sharedSecret
237.
238.     def __make_secret(self):
239.         if self.__initiator:
240.             self.__secret = self.__hash(self.__g_po, self.__g_pO, self.__g_Po)
241.         else:
242.             self.__secret = self.__hash(self.__g_po,self.__g_Po, self.__g_pO)
243.
244.     def get_secret(self):
245.         return self.__secret
246.
247. if __name__=="__main__":
248.     """
249.   Run an example Diffie-Hellman exchange
250.   """
251.     a = DiffieHellman()
252.     b = DiffieHellman()
253.     a_challenge = a.establishBase()
254.     b_challenge = b.establishBase()
255.     a.establishBase(b_challenge)
256.     b.establishBase(a_challenge)
257.     print("Established Modulo", a.diffie_base)
258.
259.     b.establishEphemeralListener()
260.     a.genPublicKey()
261.     b.genPublicKey()
262.
263.     a.genKey(b.publicKey)
264.     b.genKey(a.publicKey)
265.
266. #    a.showParams()
267. #    a.showResults()
268. #    b.showParams()
269. #    b.showResults()
270.
271.     if(a.getKey() == b.getKey()):
272.         print("Shared keys match.")
273.         print("Key:", hexlify(a.key))
274.         a_key = int(a.getKey().encode('hex'), 16)
275.         b_key = int(b.getKey().encode('hex'), 16)
276.     else:
277.         print("Shared secrets didn't match!")
278.         print("Shared secret A: ", a.genSecret(b.publicKey))
279.         print("Shared secret B: ", b.genSecret(a.publicKey))
280.
281.     a.establishAccord(b.getEphemeralPublicKey(), b.publicKey)
282.     b.establishAccord(a.getEphemeralPublicKey(), a.publicKey)
283.     if(a.get_secret() == b.get_secret()):
284.         print("Shared secrets match.")
285.         print("Key:", hexlify(a.get_secret()))
286.         a_secret = int(a.get_secret().encode('hex'), 16)
287.         b_secret = int(b.get_secret().encode('hex'), 16)
288.     else:
289.         print("Shared secrets didn't match!")
290.         print("Shared secret A: ", a.get_secret())
291.         print("Shared secret B: ", b.get_secret())
292.
293.     a.establishAccord(b.getEphemeralPublicKey(), b.publicKey)
294.     b.establishAccord(a.getEphemeralPublicKey(), a.publicKey)
295.     if(a.get_secret() == b.get_secret()):
296.         print("Shared secrets match.")
297.         print("Key:", hexlify(a.get_secret()))
298.         a_secret = int(a.get_secret().encode('hex'), 16)
299.         b_secret = int(b.get_secret().encode('hex'), 16)
300.     else:
301.         print("Shared secrets didn't match!")
302.         print("Shared secret A: ", a.get_secret())
303.         print("Shared secret B: ", b.get_secret())
304.
305.     a_point = pow(a.diffie_base, a.privateKey, a_secret) # could be a password
306.     b_point = pow(b.diffie_base, b.privateKey, b_secret)
307.     a_sync = pow(b_point, a.privateKey, a_secret)
308.     b_sync = pow(a_point, b.privateKey, a_secret)
309.
310.     a_board = pow(a_key, a_sync, a_secret)
311.     a_read = pow(a_board, a_sync, a_secret)
312.     a_echo = pow(a_read, int("Hello World".encode('hex'), 16), a_board)
313.     a_modem = pow(a_echo, a_sync, a_board)
314.
315.     b_board = pow(b_key, b_sync, b_secret)
316.     b_read = pow(b_board, b_sync, b_secret)
317.     b_echo = pow(b_read, int("Hello World".encode('hex'), 16), b_board)
318.     b_modem = pow(b_echo, b_sync, b_board)
319.
320.     a_sign = pow(a_echo, a.privateKey, a.publicKey) # Prove To The Demon That The Signs Are Different
321.     b_sign = pow(a_echo, b.privateKey, a.publicKey)
322.     b_prove = pow(a_sign, b.privateKey, a.publicKey)
323.     a_prove = pow(b_sign, a.privateKey, a.publicKey)
324.
325.     if(a_prove == b_prove):
326.         print("Shared signature verifier A matches.")
327.         print("Key: {}".format(int(hex(a_prove).encode('hex'), 16)))
328.     else:
329.         print("Shared signature verifiers didn't match!")
330.         print("Shared signature A: ", a_prove)
331.         print("Shared signature B: ", b_prove)
332.
333.     b_sign = pow(b_echo, b.privateKey, b.publicKey) # Prove To The Demon That The Signs Are Different
334.     a_sign = pow(b_echo, a.privateKey, b.publicKey)
335.     a_prove = pow(b_sign, a.privateKey, b.publicKey)
336.     b_prove = pow(a_sign, b.privateKey, b.publicKey)
337.
338.     if(a_prove == b_prove):
339.         print("Shared signature verifier B matches.")
340.         print("Key: {}".format(int(hex(b_prove).encode('hex'), 16)))
341.     else:
342.         print("Shared signature verifiers didn't match!")
343.         print("Shared signature A: ", a_prove)
344.         print("Shared signature B: ", b_prove)
345.
346.     print("board: {}\n{}".format(a_board, b_board))
347.     print("modem: {}\n{}".format(a_modem, b_modem))
348.     print("sync: {}\n{}".format(a_sync, b_sync))
350.     print("echo: {}\n{}".format(a_echo, b_echo))
351.
352.     a_prove2 = pow(a_prove, a.publicKey, b.publicKey)
353.     a_prove3 = pow(a_prove, b.publicKey, a.publicKey)
354.     b_prove2 = pow(b_prove, a.publicKey, b.publicKey)
355.     b_prove3 = pow(b_prove, b.publicKey, a.publicKey)
356.
357.     a_rectifier = pow(a_prove, a_prove2, a_prove3)
358.     b_rectifier = pow(b_prove, b_prove2, b_prove3)
359.
360.     if(a_rectifier == b_rectifier):
361.         print("Rectifier matches.")
362.         print("Key: {}".format(int(hex(a_rectifier).encode('hex'), 16)))
363.     else:
364.         print("Rectifier didn't match!")
365.         print("Rectifier A: ", a_rectifier)
366.         print("Rectifier B: ", b_rectifier)
367.
368. # Hot & Cold Redux / Color Gradient
369.     a_mass = int(hexlify(xor(to_bytes(a_rectifier), to_bytes(a_sync))), 16) # a crystal triangle chromosome
370.     b_mass = int(hexlify(xor(to_bytes(b_rectifier), to_bytes(b_sync))), 16)
371.     eS = pow(a_mass, a_board, a_sync)
372.     print("e (Fluxable): {}".format(eS))
373.     print("mass limit: {}".format(a_mass))
374.     validIntensities = 0
375.     for i in range(1, 100):
376.         b_mass_flux1 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) - i # Cold
377.         a_mass_flux1 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) - i # Cold
378.         one_degree_cold = pow(a_mass_flux1, a_modem, eS) # limit of max flux
379.         a_mass_flux2 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) + i # Hot
380.         a_mass_flux2 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) + i # Hot
381.         one_degree_hot = pow(a_mass_flux2, a_modem, eS)
382.         # Compute universal flux = avogadro's phenomenon
383.         a_flux = abs(one_degree_cold - one_degree_hot)
384.         a_weight = pow(a_read, a_rectifier, abs(a_flux)) # A Child Private Key
385. #        print("{} one degree cold: {}".format(i, one_degree_cold))
386. #        print("{} one degree hot: {}".format(i, one_degree_hot))
387. #        print("{} flux: {}".format(i, a_flux))
388. #        print("{} weight: {}".format(i, a_weight))
389.
390.         eR = pow(a_weight, a_board, a_sync)
391. #        print("{} e: {}".format(i, eR)) # R Factor
394.         a_density = pow(eR, a_flux, a_radius)
395. #        print("{} density: {}".format(i, a_density))
396.         a_coulomb = pow(a_density, a_mass, a_radius)
397. #        print("{} Coulomb: {}".format(i, a_coulomb))
398.         if a.checkPublicKey(a_coulomb):
399.             validIntensities = validIntensities + 1
400. #        print("{} Valid Private/Public Key: {}".format(i, a.checkPublicKey(a_coulomb)))
401. #        print("{} Farad: {}".format(i, pow(a.diffie_base, a_coulomb, a.prime))) # Have Enough Here To Add Peer!
402.     print("Coulombs Test: {}/100".format(validIntensities))
403.     a_catalyst = pow(a_rectifier, a_read, a_echo)
404.     b_catalyst = pow(b_rectifier, b_read, b_echo)
405.
406.     validCatalyticSeries = 0
407.     for i in range(100):
408.         a_catalyst = pow(a_catalyst, a_read, a_echo)
409.         b_catalyst = pow(b_catalyst, b_read, b_echo)
410.         if(a_catalyst == b_catalyst):
411.             validCatalyticSeries = validCatalyticSeries + 1 # Peers Could Share These As Syncs
412.
413.     if validCatalyticSeries != 100:
414.         print("Catalysis Failed, {}/100".format(validCatalyticSeries))
415.     else:
416.         print("Catalysis Test 100%!")
417.
418.     plaintext = """There is no qualification in the teacher more essen-
419. tial to his success in governing, than ability to gov-
420. ern himself;-"He that ruleth his own spirit is
421. greater than he that taketh a city;"and he who
422. cannot control himself, will succeed but poorly in his
423. attempts to control others.
424. The teacher who loses his temper, loses at the same
425. time, the respect and affection of his pupils, and af-
426. fords the mischief-loving urchin a strong temptation
427. to experiment upon his weakness. The spirit of the
428. teacher, moreover, by the force of natural sympathy,
429. communicates itself imperceptibly and unavoidably
430. to the minds of his pupils. If he be sour, morose
431. and fractious, these unamiable tempers will soon be
432. kindled in those who surround him. "Face answers
433. to face."If the teacher's countenance be clouded
434. with frowns, the dark image of his own ill-nature
435. will be reflected back upon his soul, from the group
436. of faces around him, that ought to be enlivened by
437. the constant and bright expression of his own be:
438. nignity.
439. """
440.
441.     a_atom = bytearray()
442.     a_atom += to_bytes(pow(a_catalyst, a_read, a_sync))
444.     a_echo = int(echo_transform.encode('hex'), 16)
445.     a_atom += to_bytes(a_echo.bit_length())
446.     a_atom += echo_transform
447.     a_atom += to_bytes(pow(a_catalyst, a_echo, a_sync))
448.     a_atom += to_bytes(pow(a_catalyst, a_read, a_sync))
449.
450.     b_cmdblocksize = pow(b_catalyst, b_read, b_sync).bit_length() // 8 + 1
451.     b_cmdBlock = a_atom[0:b_cmdblocksize]
452.     b_initial = (int(bytes(b_cmdBlock).encode('hex'), 16) == pow(b_catalyst, b_read, b_sync))
453.     if b_initial: #got a read block
459.         b_syncblocksize = pow(b_catalyst, int(bytes(b_readData).encode('hex'), 16), b_sync).bit_length() // 8 + 1
461.         if (int(bytes(b_checkBlock).encode('hex'), 16) != pow(b_catalyst, b_echo, b_sync)):
462.             print("Unable to verify Decryption:")
463.             print("Expected: {}".format(pow(b_catalyst, b_echo, b_sync)))
464.             print("Got: {}".format(int(bytes(b_checkBlock).encode('hex'), 16)))
466.         b_finalInitial = (int(bytes(b_syncBlock).encode('hex'), 16) == pow(b_catalyst, b_read, b_sync))
467.         if (b_finalInitial and bMsg == plaintext):
468.             print("Decryption matches:")
469.             print("Plaintext: {}".format(bMsg))
470.         else:
471.             print("Decrypt Failed!")
472.     else:
473.         print("Atom block didn't match read!")
474.         print("Expected: ", pow(b_catalyst, b_read, b_sync))