def registration_pairing(self, username, client_nonce, public_key): """Returns a random salt, ic, Server public key and combined nonce, given Client username, Client nonce and Client public key""" dh = DH() server_nonce = Utils.nonce(self.NONCE_SIZE) nonce = client_nonce + "-" + server_nonce try: self.__sessions.start_session(client_nonce) shared_key = dh.shared_secret(public_key) except SessionExistsException: raise SessionExistsException except DHBadKeyException: raise DHBadKeyException salt = Utils.nonce(self.SALT_SIZE) self.__sessions.set_session( client_nonce, { 'username': username, 'server_nonce': server_nonce, 'shared_key': shared_key, 'salt': salt }) return { "salt": salt, "ic": self.IC, "public_key": format(dh.public_key(), 'x'), "nonce": nonce }
def daemon_hound(): while 1: data = s.recv(5000) if eval(data.split("\x0f")[0])[1] == "direct" and ip in data: try: DH.hellman_client(eval(data.split("\x0f")[0])[2]) v = "h_"+eval(data.split("\x0f")[0])[0].replace(".","") time.sleep(1) exec "globals()['%s'] = DH.%s" % (v,v) while 1: globals()[v] = int(globals()[v])*32+6**2 if len(str(globals()[v])) >= 32: break globals()[v] = str(globals()[v])[:32] except: pass globals()["stop"] = True elif eval(data.split("\x0f")[0])[2] == "dm" and eval(data.split("\x0f")[0])[1] == ip: print print decrypt(data.replace("!!!key!!!",globals()[v]).replace("!!!sub!!!",globals()[v][16:]).split("\x0f")[1]) else: data = data.split("\x0f") d = decrypt(data[1]) if d != None: print "\n"+d
def dh_data(): op_type = request.form['type'] if op_type == 'genkey': keys = DH.genkey() keys_dict = { "private_keyA": hex(keys[0]), "public_keyA": (hex(keys[1][0]), hex(keys[1][1])), "private_keyB": hex(keys[2]), "public_keyB": (hex(keys[3][0]), hex(keys[3][1])), "keyAB": (hex(keys[4][0]), hex(keys[4][1])), } return jsonify(keys_dict) elif op_type == 'test': exchange = request.form['keyAB'] messageA = request.form['messageA'] keyAB = exchange.split(',') #分割 par_key = keyAB[0][2:].encode('utf-8') #0x字符串转对应hex # print(par_key) # print(type(par_key)) ans_list = DH.test(messageA, par_key) # print(ans_list) # print(type(ans_list)) message_dict = { "ciphertextA": ans_list[0], "messageB": ans_list[1], } return jsonify(message_dict)
def setPose(self, *pose): if self.currPose == pose: return else: if self.kind == 'SA': jList = ['S', 'L', 'U', 'R', 'B', 'T', 'F'] else: jList = ['S', 'L', 'U', 'R', 'B', 'T', 'F'] start = getFirstNonZeroIdx(pose, self.currPose) print('start: ', start) Tw = np.diag(np.ones(4, dtype=np.double)) if start != 0: Tw = self.linkFrames[jList[start - 1]].getTWorld() for i in range(start, len(self.DHparams)): if self.kind == 'SA': Tw = np.matmul( Tw, DH.getTCraig2(pose[i], **self.DHparams[jList[i]])) else: Tw = np.matmul( Tw, DH.getTSaha2(pose[i], **self.DHparams[jList[i]])) self.nrk.DeleteObjects([self.linkFrames[jList[i]]]) self.nrk.ConstructFrame(self.col, jList[i], Tw) self.linkFrames[jList[i]].setTWorld(Tw) self.currPose = pose pass
def stage_two(self, stage_two_msg_edge): """ Gets the public_key_edge_dh and saves it. Creates a DH key set for main and sends the public_key_main_dh. Calculates the shared key and returns it. :param stage_two_msg_edge (Bytes): public_key_edge_dh :return stage_two_msg_main (Bytes): public_key_main_dh :return shared_key: the final shared key """ self.public_key_edge_dh = int(stage_two_msg_edge.decode()) self.private_key_main_dh, self.public_key_main_dh = DH.gen_key_set() self.shared_key = DH.gen_shared_key(self.private_key_main_dh, self.public_key_edge_dh) stage_two_msg_main = str(self.public_key_main_dh).encode() return stage_two_msg_main, self.shared_key
def __init__(self, address, left=None, right=None, peer=None, dh_group=14, nonce_len=32): """ :param address: local address tuple(host, port) :param peer: remote address tuple(host, port) :param dh_group: diffie hellman group number :param nonce_len: length of Nonce data """ self.iSPI = 0 # XXX: Should be generated here and passed downwards self.rSPI = 0 self.left = left self.right = right self.diffie_hellman = dh_group # dh_group = 14 self.N = os.urandom(nonce_len) self.packets = list() self.state = State.STARTING self.address = address self.peer = peer self.dh = DH.DHE()
def __init__(self, username, password, port): ''' __init__(None) : Input : None Output : None Purpose : Constructor which initializes the Connection object 1) Reads The CLIENT.conf file and sets up essential variables 2) Reads the public_key.pem file and obtains the servers public key 3) Creates socket to talk to server ''' self.__readConfigFile() self.__username = username self.__destHostKey = {} # {Address,Key} self.__convertPasswordToSecret(password) self.__diffi = DH.DiffieHellman() self.__serverNonceHistory = [] self.__addressUserNameMap = {} self.__pubKey = self.__diffi.gen_public_key() global serverPort serverPort = int(port) try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except Exception as e: print "Error while creating socket", e sys.exit(0) with open("public_key.pem", "rb") as key_file: try: self.serverPublicKey = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) except Exception as e: print "Error while loading key ", e sys.exit(0)
def smsetup(sm): # this is Oakley group 5, actually. sm.DH = DH.construct((241031242692103258855207602219756607485695054850245994265416941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919, 2)) sm.DH.gen_key(RandomPool.get_bytes) sm.DH.groupid = 3 sm.localHIT = sm.HI.HIT127() sm.trace = 1
def setUp(self): self.SM = StateMachine(state=E0,HI=testHI) self.SM.setFQDN('1234') self.SM.localHIT = self.SM.HI.HIT127() self.SM.remoteHIT = '\xde\xad\xbe\xef\xde\xad\xbe\xef' '\xde\xad\xbe\xef\xde\xad\xbe\xef' self.SM.DH = DH.construct((0x00f488fd584e49dbcd20b49de49107366b336c380d451d0f7c88b31c7c5b2d8ef6f3c923c043f0a55b188d8ebb558cb85d38d334fd7c175743a31d186cde33212cb52aff3ce1b1294018118d7c84a70a72d686c40319c807297aca950cd9969fabd00a509b0246d3083d66a45d419f9c7cbd894b221926baaba25ec355e92f78c7, 2, 0x5a84f4b9704f010705aaf17cb14b718ad484c253bae508685583276d22e4a089bcb4e35067386250a1462a529073820f3effdc5edc39107198429fbc482c79ab07df798bc23c7517740974c542aec2b1666b59f48d06684e855e32d2e761dc8c482be9aba1bc65cbf84c6b42a11eda1a511f402c17407a31ecfeead7b48054ff, 0x15ae0584d67460bcec34efe7c32bf298a62adad0f53a00db896239e3f8949845064dcef1ad434f24237cac1ae1ea137ab6ad0234e7c742390f8d4c9f6cd8994154ba9c9b9bde38670952b5ab776c137dca1f0bdea0e951b996403fb5452b074987c6272c5099ffb97c8c87abf3f61ba346d122472e45d05f4072d8437da13bb))
def register_user(): files = [] privatekeylist = [] usernamelist = [] # Import pickle file to maintain uniqueness of the keys if (os.path.isfile("./media/database/database.pickle")): pickleObj = open("./media/database/database.pickle", "rb") privatekeylist = pickle.load(pickleObj) pickleObj.close() if (os.path.isfile("./media/database/database_1.pickle")): pickleObj = open("./media/database/database_1.pickle", "rb") usernamelist = pickle.load(pickleObj) pickleObj.close() # Declare a new list which consists all usernames if request.form['username'] in usernamelist: return render_template('register.html', name='Username already exists') username = request.form['username'] firstname = request.form['first-name'] secondname = request.form['last-name'] pin = int(random.randint(1, 128)) pin = pin % 64 #Generating a unique private key privatekey = DH.generate_private_key(pin) while privatekey in privatekeylist: privatekey = DH.generate_private_key(pin) privatekeylist.append(str(privatekey)) usernamelist.append(username) #Save/update pickle pickleObj = open("./media/database/database.pickle", "wb") pickle.dump(privatekeylist, pickleObj) pickleObj.close() pickleObj = open("./media/database/database_1.pickle", "wb") pickle.dump(usernamelist, pickleObj) pickleObj.close() #Updating a new public key for a new user filename = UPLOAD_KEY + username + '-' + secondname.upper( ) + firstname.lower() + '-PublicKey.pem' # Generate public key and save it in the file generated publickey = DH.generate_public_key(privatekey) fileObject = open(filename, "w") fileObject.write(str(publickey)) return render_template('key-display.html', privatekey=str(privatekey))
def getResidual(x, *params): Tw = np.diag(np.ones(4, dtype=np.double)) for i in range(len(x)): Tw = np.matmul(Tw, DH.getTCraig3(x[i], **params[i])) ''' Ttarg = np.array([[0.8213938, 0.42261826, -0.38302222, 1800], [0.38302222, -0.90630779, -0.1786062, 500], [-0.42261826, 0, -0.90630779, 1705], [0, 0, 0, 1]]) ''' ret = np.sum((Tw - params[-1]['target'])**2) return ret
def stage_three(self, stage_three_msg_main): """ Gets the public_key_main_dh, calculates the shared key and saves it. sends a random ACK message that will be encrypted and signed with the shared key. :param stage_three_msg_main (Bytes): public_key_main_dh :return Ack message (Bytes): A random ack message :return shared_key (Str): The shared_key """ self.public_key_main_dh = int(stage_three_msg_main.decode()) self.shared_key = DH.gen_shared_key(self.private_key_edge_dh, self.public_key_main_dh) ack = ''.join(random.choice(string.printable) for i in range(128)).encode() signature = zRSA.sign_data(ack, self.private_rsa_edge) return ack, signature, self.shared_key
def fLeg(thetas, lorr ): #HipYawPitch HipRoll HipPitch KneePitch AnklePitch AnkleRoll T1-T6 #unit CM base = np.eye(4) if lorr == 'r': base[1][3] = -HipOffsetY T1 = DH(0, -pi / 4, 0, thetas[0] - pi / 2) dT1 = DHDerivative(0, -pi / 4, 0, thetas[0] - pi / 2) T2 = DH(0, -pi / 2, 0, thetas[1] - pi / 4) #+- left right diff? dT2 = DHDerivative(0, -pi / 2, 0, thetas[1] - pi / 4) elif lorr == 'l': base[1][3] = HipOffsetY T1 = DH(0, -3 * pi / 4, 0, thetas[0] - pi / 2) dT1 = DHDerivative(0, -3 * pi / 4, 0, thetas[0] - pi / 2) T2 = DH(0, -pi / 2, 0, thetas[1] + pi / 4) #+- left right diff? dT2 = DHDerivative(0, -pi / 2, 0, thetas[1] + pi / 4) base[2][3] = -HipOffsetZ T3 = DH(0, pi / 2, 0, thetas[2]) dT3 = DHDerivative(0, pi / 2, 0, thetas[2]) T4 = DH(-ThighLength, 0, 0, thetas[3]) dT4 = DHDerivative(-ThighLength, 0, 0, thetas[3]) T5 = DH(-TibiaLength, 0, 0, thetas[4]) dT5 = DHDerivative(-TibiaLength, 0, 0, thetas[4]) T6 = DH(0, -pi / 2, 0, thetas[5]) dT6 = DHDerivative(0, -pi / 2, 0, thetas[5]) Tend = rotZYX(pi, -pi / 2, 0) #?? Tend1 = np.eye(4) Tend1[2][3] = -FootHeight Tendend = reduce(np.dot, [base, T1, T2, T3, T4, T5, T6, Tend, Tend1]) Derivatives1 = reduce(np.dot, [base, dT1, T2, T3, T4, T5, T6, Tend, Tend1]) Derivatives2 = reduce(np.dot, [base, T1, dT2, T3, T4, T5, T6, Tend, Tend1]) Derivatives3 = reduce(np.dot, [base, T1, T2, dT3, T4, T5, T6, Tend, Tend1]) Derivatives4 = reduce(np.dot, [base, T1, T2, T3, dT4, T5, T6, Tend, Tend1]) Derivatives5 = reduce(np.dot, [base, T1, T2, T3, T4, dT5, T6, Tend, Tend1]) Derivatives6 = reduce(np.dot, [base, T1, T2, T3, T4, T5, dT6, Tend, Tend1]) Derivatives = np.array([ Derivatives1, Derivatives2, Derivatives3, Derivatives4, Derivatives5, Derivatives6 ]) rotZ = math.atan2(Tendend[1][0], Tendend[0][0]) rotY = math.atan2(-Tendend[2][0], math.sqrt(Tendend[2][1]**2 + Tendend[2][2]**2)) rotX = math.atan2(Tendend[2][1], Tendend[2][2]) #print Tendend #print (rotX,rotY,rotZ) return (Tendend, Derivatives)
def decrypt(filename, directory, public_key, private_key): key = DH.generateSecret(long(private_key), long(public_key)) str = key.encode('hex') key = str[0:32] file_obj = open(filename, "r") msg = file_obj.read() text = ENCDEC.AESCipher(key).decrypt(msg) outputFilename = os.path.join(directory, "DecodedFile.txt") file_obj = open(outputFilename, "w") file_obj.write(text) os.remove(filename) os.system("xdg-open " + directory)
def genRobot(self): if self.kind == 'SA': jList = ['S', 'L', 'U', 'R', 'B', 'T', 'F'] else: jList = ['S', 'L', 'U', 'R', 'B', 'T', 'F'] Tw = np.diag(np.ones(4, dtype=np.double)) params = {} params['col'] = self.col for j in range(len(self.DHparams)): if self.kind == 'SA': Tcurr = DH.getTCraig2(self.homePose[j], **self.DHparams[jList[j]]) else: Tcurr = DH.getTSaha2(self.homePose[j], **self.DHparams[jList[j]]) Tw = np.matmul(Tw, Tcurr) params['name'] = jList[j] params['TWorld'] = Tw self.linkFrames[jList[j]] = frame.frame(**params) self.nrk.ConstructFrame(self.col, jList[j], Tcurr) self.nrk.SetWorkingFrame(self.col, jList[j]) self.nrk.SetWorkingFrame("A", "World") self.currPose = self.homePose
def encrypt(filename, directory, public_key, private_key): key = DH.generateSecret(long(private_key), long(public_key)) str = key.encode('hex') key = str[0:32] file_obj = open(filename, "r") t = time.time() msg1 = ENCDEC.AESCipher(key).encrypt(file_obj.read()) s = time.time() outputFilename = os.path.join(directory, key[16:] + ".txt") file_obj = open(outputFilename, 'w') file_obj.write(msg1) os.remove(filename) os.system("xdg-open " + directory)
def stage_two(self, stage_two_msg_main, dh_signature): """ Gets the public_key_rsa_main as the stage_two_msg_main. The dh_signature Sends the public_key_edge_dh :param stage_two_msg_main (bytes): data from main :param dh_signature (bytes): dh_signature from main :return stage_two_msg_edge(Bytes)/ False: False if the signature failed. public_key_edge_dh if the signature is good. """ to_verify_sig = (zRSA.public_key_to_bytes(stage_two_msg_main) + zRSA.public_key_to_bytes(self.public_rsa_edge)) if zRSA.verify_signature(to_verify_sig, self.PUBLIC_KEY_MASTER_GLOBAL, dh_signature, 1.2) is False: return False self.public_rsa_main = stage_two_msg_main self.private_key_edge_dh, self.public_key_edge_dh = DH.gen_key_set() stage_two_msg_edge = str(self.public_key_edge_dh).encode() return stage_two_msg_edge
def decrypt(filename,directory,public_key,private_key): key = DH.generate_secret(int(private_key), int(public_key)) str = key.encode('utf-8').hex() key = str[0:32] file_obj = open(filename,"r") msg = file_obj.read() #list = msg.split('\n') #msg1 = list[0] #msg2 = list[2] text = ENCDEC.AESCipher(key).decrypt(msg) #msg2 = ENCDEC.AESCipher(key).decrypt(msg2) #temp = [] #temp.append(unicodedata.normalize('NFKD',msg1).encode('ascii','ignore')) #temp.append(list[1]) #text = ENCDEC.shamirs_join(temp,unicodedata.normalize('NFKD',msg2).encode('ascii','ignore')) #outputFilename = os.path.join(directory,"DecodedFile.txt") #file_obj = open(outputFilename,"w") #file_obj.write(text) os.remove(filename)
def __init__(self): ''' __init__(None): Input : None Output : None Purpose : 1) Initialise objects to maintain connection state 2) Read server private key for future use ''' self.__diffiObj = DH.DiffieHellman() self.__authDict = {} self.__sessionKeyDict = {} # username : [key,address] self.__userNonceHistor = {} # nonce : bool self.__connectedClients = {} # address : username with open("private_key.pem", "rb") as key_file: try: self.__privateKey = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) except: print "Error while Loading key " + file sys.exit(0)
def encrypt(filename,directory,public_key,private_key): key = DH.generate_secret(int(private_key), int(public_key)) str = key.encode('utf-8').hex() key = str[0:32] file_obj = open(filename,"r") t = time.time() #list,str = ENCDEC.shamirs_split(file_obj) msg1 = ENCDEC.AESCipher(key).encrypt(file_obj.read()) #msg2 = ENCDEC.AESCipher(key).encrypt(str) s = time.time() #Exchange this with public key outputFilename = os.path.join(directory,key[16:]+".txt") file_obj = open(outputFilename,'w') file_obj.write(msg1) #file_obj.write('\n') #file_obj.write(list[1]) #file_obj.write('\n') #file_obj.write(msg2) os.remove(filename)
def __init__(self, host, queue, interfaces, hit='', fqdn=''): #print 'New StateMachine:', fqdn, repr(hit), repr(self), self.canpiggyback HIPState.StateMachine.__init__(self, state=HIPState.E0, HI=host.hi) ## # this is MODP group 5, actually. ## self.DH = DH.construct((241031242692103258855207602219756607485695054850245994265416941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919, ## 2)) self.DH = DH.construct(( 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF, 2)) self.DH.groupid = 3 self.localHIT = self.HI.HIT127() #self.localHIT = self.HI.HIT64(unhexlify('9e800000000000000000000000000000')) self.DH.gen_key(RandomPool.get_bytes) self.setFQDN(fqdn) self.remoteHIT = hit self.OutQueue = queue self.piggyback = 0 self.LSIcallback = host.LSIcallback self.lifetime = 9000 #seconds self.rekey = 6000 #seconds self.lastused = time.time() self.lastkeyed = time.time() self.rekeying = 0 self.trace = 1 self.interfaces = interfaces self.setLocalIPs(self.interfaces) self.useIPv6 = 0 def cb(host, m): k = Future(m.DH.gen_key(RandomPool.get_bytes)) if host.useIPv6: m.useIPv6 = host.useIPv6 m.localESP.remoteIPv6addr = m.remoteHI.HITv6link() m.localESP.localIPv6addr = host.hi.HITv6link() m.remoteESP.remoteIPv6addr = m.localESP.remoteIPv6addr m.remoteESP.localIPv6addr = m.localESP.localIPv6addr self.E3callback = curryl(cb, host) self.callbacks[HIPState.E3] = self.E3callback
for k in range(-35, 35): theta1 = delta_theta1 * i theta2 = delta_theta2 * j theta3 = delta_theta3 * k # radius to degree change = 180 / pi # forward kinematics state vector q = array([[change * theta1], [change * theta2], [change * theta3], [change * theta4], [change * theta5], [change * theta6]]) ## Forward Kinematics # homogeneous transformation matrix A01 = DH(theta1, alpha1, a1, d1) A12 = DH(theta2, alpha2, a2, d2) A23 = DH(theta3, alpha3, a3, d3) A34 = DH(theta4, alpha4, a4, d4) A45 = DH(theta5, alpha5, a5, d5) A56 = DH(theta6, alpha6, a6, d6) T1 = A01 T2 = dot(T1, A12) T3 = dot(T2, A23) T4 = dot(T3, A34) T5 = dot(T4, A45) T6 = dot(T5, A56) # obtain z1 z1x = T1[0, 2]
class Client(object): """Client class: It permits to register and authenticate to a Server Attributes: __dh: A Diffie Hellman class Constants: NONCE_SIZE: nonce size in bits """ NONCE_SIZE = 32 def __init__(self): self.__dh = DH() def _check_nonce(self, nonce): """It verifies the correctness of a given nonce""" if nonce.count('-') != 1: raise ClientNonceException try: client_nonce, server_nonce = nonce.split("-") except ClientNonceException: raise ClientNonceException return client_nonce, server_nonce def registration_pairing(self, username, password): """Returns dictionary with username, public key and a random Client nonce""" self.__data = { "username": username, "password": password, "nonce": Utils.nonce(self.NONCE_SIZE) } return { "username": self.__data['username'], "public_key": format(self.__dh.public_key(), 'x'), "client_nonce": self.__data['nonce'] } def registration_send_password(self, salt, ic, public_key, nonce): """Returns encrypted salted password and combined nonce, given salt, ic, Server public key and Server nonce by the Server""" try: self.__data['shared_key'] = self.__dh.shared_secret(public_key) client_nonce, server_nonce = self._check_nonce(nonce) except DHBadKeyException: raise DHBadKeyException except ClientNonceException: raise ClientNonceException if client_nonce != self.__data['nonce']: raise ClientNonceException self.__data['nonce'] = client_nonce + "-" + server_nonce self.__data['salted_password'] = Scram.salted_password( self.__data['password'], salt, ic) secret_salted_password = Utils.bitwise_xor( self.__data['salted_password'], self.__data['shared_key']) return { "secret_key": secret_salted_password, "nonce": self.__data['nonce'], } def registration_keys_generation(self, secret_server_key, secret_client_key, nonce): """Returns Client key, server key and stored key, given encrypted "Server key" and encrypted "Slient key" and combined nonce""" if self.__data['nonce'] != nonce: raise ClientNonceException client_key = Utils.bitwise_xor(secret_client_key, self.__data['shared_key']) server_key = Utils.bitwise_xor(secret_server_key, self.__data['shared_key']) client_client_key = Utils.hmac_generation( self.__data['salted_password'], client_key) client_server_key = Utils.hmac_generation( self.__data['salted_password'], server_key) client_stored_key = Scram.stored_key_generation(client_client_key) return_value = { "server_key": client_server_key, "client_key": client_client_key, "stored_key": client_stored_key } self.__data = {} self.__data = { "server_key": client_server_key, "client_key": client_client_key, "stored_key": client_stored_key } return return_value def auth_pairing(self, username, client_key, server_key): """Returns username and a random Client nonce, given Client key and Server key""" self.__data['nonce'] = Utils.nonce(self.NONCE_SIZE) self.__data['username'] = username self.__data['client_key'] = client_key self.__data['server_key'] = server_key self.__data['stored_key'] = Scram.stored_key_generation( self.__data['client_key']) return {"username": username, "client_nonce": self.__data['nonce']} def auth_client_proof_generation(self, nonce, salt, ic): """Returns combined nonce and Client proof, given combined nonce, salt and ic by the Server""" try: client_nonce, server_nonce = self._check_nonce(nonce) except ClientNonceException: raise ClientNonceException if client_nonce != self.__data['nonce']: raise ClientNonceException self.__data['auth_message'] = Scram.auth_message_generation( self.__data['username'], client_nonce, salt, ic, server_nonce) client_signature = Scram.signature_generation( self.__data['stored_key'], self.__data['auth_message']) self.__data['client_proof'] = Scram.client_proof_generation( self.__data['client_key'], client_signature) return {"nonce": nonce, "client_proof": self.__data['client_proof']} def server_auth(self, server_signature): """Verifies the correctness of the given Server signature""" client_server_signature = Scram.signature_generation( self.__data['server_key'], self.__data['auth_message']) if client_server_signature != server_signature: raise Exception("Verification failed")
import DH if __name__ == "__main__": # 1. 初始化密钥交换的双方A和B A = DH.DeffieHellman() B = DH.DeffieHellman() # 2. 密钥交换双方的其中一方A生成共享参数——素数q及其本原根a q, a = A.generateArg() # 3. 密钥交换的双方A,B利用上述素数q和本原根a生成各自的公钥和私钥,并共享A,B各自的公钥Ya,Yb Ya = A.generateKey(q, a) Yb = B.generateKey(q, a) # 4. 输出双方的共享参数q, a,以及双方各自的公钥Ya,Yb (qa, aa, Ya) = A.publish() (qb, ab, Yb) = B.publish() print("A的公开参数q = ", qa) print("A的公开参数a = ", aa) print("A的公钥Ya = ", Ya) print("B的公开参数q = ", qb) print("B的公开参数a = ", ab) print("B的公钥Yb = ", Yb) # 5. A根据公钥Yb计算出共享密钥并输出 keya = A.getKey(Yb) print("A计算出的共享密钥为: ", keya) # 6. B根据公钥Ya计算出共享密钥并输出 keyb = B.getKey(Ya) print("B计算出的共享密钥为: ", keyb)
def encryptdh(): string = DH.encrypt(request.json['text']) sr = DH.decrypt(string) return jsonify(encrypt = string, decrypt = sr)
def getdh(): g, p, a, b, A, B, K1, K2 = DH.getDH() return jsonify(g = g, p = p, a = a, b = b, A = A, B = B, K1 = K1, K2 = K2)
def __init__(self): self.__dh = DH()
def forward(joint_var): #put the values in the DH_table for i in range(6): DH.DH_table[i][0] = joint_var[0] * sp.pi / 180 return DH.Robot_matrix()
elif eval(data.split("\x0f")[0])[2] == "dm" and eval(data.split("\x0f")[0])[1] == ip: print print decrypt(data.replace("!!!key!!!",globals()[v]).replace("!!!sub!!!",globals()[v][16:]).split("\x0f")[1]) else: data = data.split("\x0f") d = decrypt(data[1]) if d != None: print "\n"+d daemon = threading.Thread(target=daemon_hound) daemon.daemon = True daemon.start() print "[DAEMON] SNIFFING" time.sleep(0.5) DH.hellman() time.sleep(0.5) stop = False while 1: try: msg = raw_input("\n=> ") except: break if len(msg) == 0: msg = "0" data = header() + encrypt(user+msg,key) d_host = raw_input("HOST => ") direct = header("direct",d_host) if len(d_host) > 7: data = direct