""" Perceive Cryptography Algorythm In Python 2.7 Perform a series of Diffie-Hellman exchanges to perceive a common data point without communicating it then use this data point as the modulo for encryption """ import hashlib import random from binascii import hexlify # For debug output import json import sys # If a secure random number generator is unavailable, exit with an error. try: import ssl random_function = ssl.RAND_bytes random_provider = "Python SSL" except (AttributeError, ImportError): import OpenSSL random_function = OpenSSL.rand.bytes random_provider = "OpenSSL" def xor(data, key): return bytearray(a^b for a, b in zip(*map(bytearray, [data, key]))) def quad(a, x, b, c): blocksize = x.bit_length() // 8 + 1 blocks = [a[i:i+blocksize] for i in range(0, len(a), blocksize)] y = bytearray() catalyst = pow(x, b, c) for i in range(len(blocks)): catalyst = pow(catalyst, b, c) # print("{} : {}".format(i, catalyst)) y += xor(blocks[i], to_bytes(catalyst, blocksize, byteorder="big")) return y def to_bytes(n, length=32, byteorder="big"): h = '%x' %n s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex') return s if byteorder =='big' else s[::-1] class DiffieHellman(object): """ A reference implementation of the Diffie-Hellman protocol. By default, this class uses 1536-bit MODP Group From RFC3526. """ def __init__(self, privateKey=None, keyLength=2048): """ Generate the public and private keys. """ min_keyLength = 180 self.diffie_base = 2 # base g from Diffie's protocol self.starter_base = 5 self.starter_prime = 101 self.__fingerprint = None self.__secret = random.randint(500,sys.maxint) self.__g_po = None self.__g_pO = None self.__g_Po = None self.__ephemeralKey = None self.__initiator = True self.publicKey = None if(keyLength < min_keyLength): print("Error: keyLength is too small. Setting to minimum.") self.keyLength = min_keyLength else: self.keyLength = keyLength # RFC3526 1536-bit MODP Group self.prime = int('0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC7' '4020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDE' 'E386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598' 'DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED' '529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF', 16) if privateKey is None: self.privateKey = self.genPrivateKey(keyLength) else: self.privateKey = privateKey self.publicKey = self.genPublicKey() # regenerate this after establishBase() def establishBase(self, challenge=None): if challenge is None: return pow(self.starter_base, self.__secret, self.starter_prime) else: self.diffie_base = pow(challenge, self.__secret, self.starter_prime) self.genPublicKey() # regenerate public key after changing base def genPrivateKey(self, bits): """ Generate a private key using a secure random number generator. """ return self.genRandom(bits) def genPublicKey(self): """ Generate a public key X with g**x % p. """ return pow(self.diffie_base, self.privateKey, self.prime) def genRandom(self, bits): """ Generate a random number with the specified number of bits """ _rand = 0 _bytes = bits // 8 + 8 while(_rand.bit_length() < bits): try: # Python 3 _rand = int.from_bytes(random_function(_bytes), byteorder='big') except: # Python 2 _rand = int(OpenSSL.rand.bytes(_bytes).encode('hex'), 16) return _rand def genKey(self, otherKey): """ Derive the shared secret, then hash it to obtain the shared key. """ self.sharedSecret = self.genSecret(self.privateKey, otherKey) # Convert the shared secret (int) to an array of bytes in network order # Otherwise hashlib can't hash it. try: _sharedSecretBytes = self.sharedSecret.to_bytes(self.sharedSecret.bit_length() // 8 + 1, byteorder="big") except AttributeError: _sharedSecretBytes = str(self.sharedSecret) s = hashlib.sha256() s.update(bytes(_sharedSecretBytes)) self.key = s.digest() def checkPublicKey(self, otherKey): """ Check the other party's public key to make sure it's valid. Since a safe prime is used, verify that the Legendre symbol == 1 """ if(otherKey > 2 and otherKey < self.prime - 1): if(pow(otherKey, (self.prime - 1)//2, self.prime) == 1): return True return False def genSecret(self, privateKey, otherKey): """ Check to make sure the public key is valid, then combine it with the private key to generate a shared secret. """ if(self.checkPublicKey(otherKey) == True): sharedSecret = pow(otherKey, privateKey, self.prime) return sharedSecret else: raise Exception("Invalid public key.") def showParams(self): """ Show the parameters of the Diffie Hellman agreement. """ print("Parameters:") print("Prime[{0}]: {1}".format(self.prime.bit_length(), self.prime)) print("Private key[{0}]: {1}\n".format(self.privateKey.bit_length(), self.privateKey)) print("Public key[{0}]: {1}".format(self.publicKey.bit_length(), self.publicKey)) def showResults(self): """ Show the results of a Diffie-Hellman exchange. """ print("Results:") print("Shared secret[{0}]: {1}".format(self.sharedSecret.bit_length(), self.sharedSecret)) print("Shared key[{0}]: {1}".format(len(self.key), hexlify(self.key))) def getKey(self): """ Return the shared secret key """ return self.key def get_fingerprint(self): if self.__fingerprint: return self.__fingerprint publicKey = self.publicKey return self.__make_fingerprint(publicKey) def __make_fingerprint(self, pub_key): self.__fingerprint = self.__hash(pub_key) return self.__fingerprint def __hash(self, *values): """Hashes the concatenation of values each element in values must be of type int """ s = hashlib.sha256() for value in values: try: value_bytes = to_bytes(value, value.bit_length() // 8 + 1, byteorder="big") except AttributeError: value_bytes = str(value) s.update(bytes(value_bytes)) return s.digest() def establishAccord(self, party_ephemeral, party_signature=None): if party_signature is not None: self.handshake(party_ephemeral, party_signature) def getEphemeralPublicKey(self): return self.__ephemeralKey.publicKey def establishEphemeralListener(self): self.__ephemeralKey = DiffieHellman() self.__initiator = False def handshake(self, party_ephemeral, party_signature): if self.__initiator: self.__ephemeralKey = DiffieHellman() fingerprint = self.__make_fingerprint(party_signature) self.__ephemeralKey.genKey(party_ephemeral) self.__g_po = self.__ephemeralKey.getSecret() self.__ephemeralKey.genKey(party_signature) self.__g_pO = self.__ephemeralKey.getSecret() self.genKey(party_ephemeral) self.__g_Po = self.getSecret() self.__make_secret() def getSecret(self): """ Return the preHashed key """ return self.sharedSecret def __make_secret(self): if self.__initiator: self.__secret = self.__hash(self.__g_po, self.__g_pO, self.__g_Po) else: self.__secret = self.__hash(self.__g_po,self.__g_Po, self.__g_pO) def get_secret(self): return self.__secret if __name__=="__main__": """ Run an example Diffie-Hellman exchange """ a = DiffieHellman() b = DiffieHellman() a_challenge = a.establishBase() b_challenge = b.establishBase() a.establishBase(b_challenge) b.establishBase(a_challenge) print("Established Modulo", a.diffie_base) b.establishEphemeralListener() a.genPublicKey() b.genPublicKey() a.genKey(b.publicKey) b.genKey(a.publicKey) # a.showParams() # a.showResults() # b.showParams() # b.showResults() if(a.getKey() == b.getKey()): print("Shared keys match.") print("Key:", hexlify(a.key)) a_key = int(a.getKey().encode('hex'), 16) b_key = int(b.getKey().encode('hex'), 16) else: print("Shared secrets didn't match!") print("Shared secret A: ", a.genSecret(b.publicKey)) print("Shared secret B: ", b.genSecret(a.publicKey)) a.establishAccord(b.getEphemeralPublicKey(), b.publicKey) b.establishAccord(a.getEphemeralPublicKey(), a.publicKey) if(a.get_secret() == b.get_secret()): print("Shared secrets match.") print("Key:", hexlify(a.get_secret())) a_secret = int(a.get_secret().encode('hex'), 16) b_secret = int(b.get_secret().encode('hex'), 16) else: print("Shared secrets didn't match!") print("Shared secret A: ", a.get_secret()) print("Shared secret B: ", b.get_secret()) a.establishAccord(b.getEphemeralPublicKey(), b.publicKey) b.establishAccord(a.getEphemeralPublicKey(), a.publicKey) if(a.get_secret() == b.get_secret()): print("Shared secrets match.") print("Key:", hexlify(a.get_secret())) a_secret = int(a.get_secret().encode('hex'), 16) b_secret = int(b.get_secret().encode('hex'), 16) else: print("Shared secrets didn't match!") print("Shared secret A: ", a.get_secret()) print("Shared secret B: ", b.get_secret()) a_point = pow(a.diffie_base, a.privateKey, a_secret) # could be a password b_point = pow(b.diffie_base, b.privateKey, b_secret) a_sync = pow(b_point, a.privateKey, a_secret) b_sync = pow(a_point, b.privateKey, a_secret) a_board = pow(a_key, a_sync, a_secret) a_read = pow(a_board, a_sync, a_secret) a_echo = pow(a_read, int("Hello World".encode('hex'), 16), a_board) a_modem = pow(a_echo, a_sync, a_board) b_board = pow(b_key, b_sync, b_secret) b_read = pow(b_board, b_sync, b_secret) b_echo = pow(b_read, int("Hello World".encode('hex'), 16), b_board) b_modem = pow(b_echo, b_sync, b_board) a_sign = pow(a_echo, a.privateKey, a.publicKey) # Prove To The Demon That The Signs Are Different b_sign = pow(a_echo, b.privateKey, a.publicKey) b_prove = pow(a_sign, b.privateKey, a.publicKey) a_prove = pow(b_sign, a.privateKey, a.publicKey) if(a_prove == b_prove): print("Shared signature verifier A matches.") print("Key: {}".format(int(hex(a_prove).encode('hex'), 16))) else: print("Shared signature verifiers didn't match!") print("Shared signature A: ", a_prove) print("Shared signature B: ", b_prove) b_sign = pow(b_echo, b.privateKey, b.publicKey) # Prove To The Demon That The Signs Are Different a_sign = pow(b_echo, a.privateKey, b.publicKey) a_prove = pow(b_sign, a.privateKey, b.publicKey) b_prove = pow(a_sign, b.privateKey, b.publicKey) if(a_prove == b_prove): print("Shared signature verifier B matches.") print("Key: {}".format(int(hex(b_prove).encode('hex'), 16))) else: print("Shared signature verifiers didn't match!") print("Shared signature A: ", a_prove) print("Shared signature B: ", b_prove) print("board: {}\n{}".format(a_board, b_board)) print("modem: {}\n{}".format(a_modem, b_modem)) print("sync: {}\n{}".format(a_sync, b_sync)) print("read: {}\n{}".format(a_read, b_read)) print("echo: {}\n{}".format(a_echo, b_echo)) a_prove2 = pow(a_prove, a.publicKey, b.publicKey) a_prove3 = pow(a_prove, b.publicKey, a.publicKey) b_prove2 = pow(b_prove, a.publicKey, b.publicKey) b_prove3 = pow(b_prove, b.publicKey, a.publicKey) a_rectifier = pow(a_prove, a_prove2, a_prove3) b_rectifier = pow(b_prove, b_prove2, b_prove3) if(a_rectifier == b_rectifier): print("Rectifier matches.") print("Key: {}".format(int(hex(a_rectifier).encode('hex'), 16))) else: print("Rectifier didn't match!") print("Rectifier A: ", a_rectifier) print("Rectifier B: ", b_rectifier) # Hot & Cold Redux / Color Gradient a_mass = int(hexlify(xor(to_bytes(a_rectifier), to_bytes(a_sync))), 16) # a crystal triangle chromosome b_mass = int(hexlify(xor(to_bytes(b_rectifier), to_bytes(b_sync))), 16) eS = pow(a_mass, a_board, a_sync) print("e (Fluxable): {}".format(eS)) print("mass limit: {}".format(a_mass)) validIntensities = 0 for i in range(1, 100): b_mass_flux1 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) - i # Cold a_mass_flux1 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) - i # Cold one_degree_cold = pow(a_mass_flux1, a_modem, eS) # limit of max flux a_mass_flux2 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) + i # Hot a_mass_flux2 = int(hexlify(xor(to_bytes(a_sync), to_bytes(a_rectifier))), 16) + i # Hot one_degree_hot = pow(a_mass_flux2, a_modem, eS) # Compute universal flux = avogadro's phenomenon a_flux = abs(one_degree_cold - one_degree_hot) a_weight = pow(a_read, a_rectifier, abs(a_flux)) # A Child Private Key # print("{} one degree cold: {}".format(i, one_degree_cold)) # print("{} one degree hot: {}".format(i, one_degree_hot)) # print("{} flux: {}".format(i, a_flux)) # print("{} weight: {}".format(i, a_weight)) eR = pow(a_weight, a_board, a_sync) # print("{} e: {}".format(i, eR)) # R Factor a_radius = int(bytes(quad(to_bytes(a_weight), a_flux, eS, eR)).encode('hex'), 16) # print("{} radius: {}".format(i, a_radius)) a_density = pow(eR, a_flux, a_radius) # print("{} density: {}".format(i, a_density)) a_coulomb = pow(a_density, a_mass, a_radius) # print("{} Coulomb: {}".format(i, a_coulomb)) if a.checkPublicKey(a_coulomb): validIntensities = validIntensities + 1 # print("{} Valid Private/Public Key: {}".format(i, a.checkPublicKey(a_coulomb))) # print("{} Farad: {}".format(i, pow(a.diffie_base, a_coulomb, a.prime))) # Have Enough Here To Add Peer! print("Coulombs Test: {}/100".format(validIntensities)) a_catalyst = pow(a_rectifier, a_read, a_echo) b_catalyst = pow(b_rectifier, b_read, b_echo) validCatalyticSeries = 0 for i in range(100): a_catalyst = pow(a_catalyst, a_read, a_echo) b_catalyst = pow(b_catalyst, b_read, b_echo) if(a_catalyst == b_catalyst): validCatalyticSeries = validCatalyticSeries + 1 # Peers Could Share These As Syncs if validCatalyticSeries != 100: print("Catalysis Failed, {}/100".format(validCatalyticSeries)) else: print("Catalysis Test 100%!") plaintext = """There is no qualification in the teacher more essen- tial to his success in governing, than ability to gov- ern himself;-"He that ruleth his own spirit is greater than he that taketh a city;"and he who cannot control himself, will succeed but poorly in his attempts to control others. The teacher who loses his temper, loses at the same time, the respect and affection of his pupils, and af- fords the mischief-loving urchin a strong temptation to experiment upon his weakness. The spirit of the teacher, moreover, by the force of natural sympathy, communicates itself imperceptibly and unavoidably to the minds of his pupils. If he be sour, morose and fractious, these unamiable tempers will soon be kindled in those who surround him. "Face answers to face."If the teacher's countenance be clouded with frowns, the dark image of his own ill-nature will be reflected back upon his soul, from the group of faces around him, that ought to be enlivened by the constant and bright expression of his own be: nignity. """ a_atom = bytearray() a_atom += to_bytes(pow(a_catalyst, a_read, a_sync)) echo_transform = bytes(quad(plaintext, a_catalyst, a_read, a_echo)) a_echo = int(echo_transform.encode('hex'), 16) a_atom += to_bytes(a_echo.bit_length()) a_atom += echo_transform a_atom += to_bytes(pow(a_catalyst, a_echo, a_sync)) a_atom += to_bytes(pow(a_catalyst, a_read, a_sync)) b_cmdblocksize = pow(b_catalyst, b_read, b_sync).bit_length() // 8 + 1 b_cmdBlock = a_atom[0:b_cmdblocksize] b_initial = (int(bytes(b_cmdBlock).encode('hex'), 16) == pow(b_catalyst, b_read, b_sync)) if b_initial: #got a read block b_readSizeBlock = a_atom[b_cmdblocksize:b_cmdblocksize*2] b_readBlocks = int(bytes(b_readSizeBlock).encode('hex'), 16) // 8 + 1 b_readData = a_atom[b_cmdblocksize*2:b_cmdblocksize*2+b_readBlocks] bMsg = quad(b_readData, b_catalyst, b_read, b_echo) b_echo = int(bytes(b_readData).encode('hex'), 16) b_syncblocksize = pow(b_catalyst, int(bytes(b_readData).encode('hex'), 16), b_sync).bit_length() // 8 + 1 b_checkBlock = a_atom[b_cmdblocksize*2+b_readBlocks:b_cmdblocksize*2+b_readBlocks+b_syncblocksize] if (int(bytes(b_checkBlock).encode('hex'), 16) != pow(b_catalyst, b_echo, b_sync)): print("Unable to verify Decryption:") print("Expected: {}".format(pow(b_catalyst, b_echo, b_sync))) print("Got: {}".format(int(bytes(b_checkBlock).encode('hex'), 16))) b_syncBlock = a_atom[b_cmdblocksize+b_cmdblocksize+b_readBlocks+b_syncblocksize:] b_finalInitial = (int(bytes(b_syncBlock).encode('hex'), 16) == pow(b_catalyst, b_read, b_sync)) if (b_finalInitial and bMsg == plaintext): print("Decryption matches:") print("Plaintext: {}".format(bMsg)) else: print("Decrypt Failed!") else: print("Atom block didn't match read!") print("Expected: ", pow(b_catalyst, b_read, b_sync)) print("Received: ", int(bytes(b_cmdBlock).encode('hex'), 16))