def TGS_server(info: dict): tgt_encr = info['tgt'] auth_encr = info['auth'] service_id = info['id'] tgt = DES.decrypt(tgt_encr, database.K_as_tgs) tgt = eval(tgt) k_c_tgs = tgt['key'] auth = DES.decrypt(auth_encr, tgt['key']) auth = eval(auth) if auth['c'] != tgt['c']: raise ValueError('client id not equal') if auth['time'] - tgt['time'] > tgt['period']: raise ValueError('ticket is not valid') k_tgs_ss = database.keys[(service_id, database.tgs_id)] k_c_ss = database.keys[tuple(sorted((service_id, auth['c'])))] tgs = { 'c': auth['c'], 'ss': service_id, 'time': datetime.now().timestamp(), 'period': 1000, 'key': k_c_ss } res = { 'tgs': DES.encrypt(str(tgs), k_tgs_ss), 'key': k_c_ss } return DES.encrypt(str(res), k_c_tgs)
def generate_session(username, password, servername, network_address): global i i += 1 key = hash.generate_session() # key for the session dateTimeObj = datetime.now() # gets the current timestamp timestampStr = dateTimeObj.strftime( "%Y-%m-%d %H:%M:%S.%f") # converts the timestamp to a readable format life = str(dateTimeObj + timedelta(hours=1)) # lifetime for the generated ticket print(i, timestampStr) # Create the ticket with correct parameters and encrypt it using DES ticket = '{{"username":"******","server":"{}","network":"{}","sessionkey":"{}","timestamp":"{}","lifetime":"{}"}}'.format( username, servername, network_address, key, timestampStr, life) print(i, ticket) eTicket = DES.encrypt(IOTKEY[:8], ticket) eticket_str = base64.b64encode(eTicket).decode("utf-8") payload = '{{"sessionkey":"{}","timestamp":"{}","lifetime":"{}","ticket":"{}"}}'.format( key, timestampStr, life, eticket_str) # # Encrypt the client's key using DES client_key = base64.b64decode(password) cipher = DES.encrypt(client_key[48:56], payload) # Add a salt to the password hash and return the packet salt = base64.b64encode(client_key[:32]).decode("utf-8") return_packet = '{{"salt":"{}","payload":"{}"}}'.format( salt, base64.b64encode(cipher).decode("utf-8")) return return_packet.encode()
def generate_session(username, password, servername, network_address): global i i += 1 key = hash.generate_session() dateTimeObj = datetime.now() timestampStr = dateTimeObj.strftime("%Y-%m-%d %H:%M:%S.%f") life = str(dateTimeObj + timedelta(hours=1)) print(i, timestampStr) ticket = '{{"username":"******","server":"{}","network":"{}","sessionkey":"{}","timestamp":"{}","lifetime":"{}"}}'.format( username, servername, network_address, key, timestampStr, life) print(i, ticket) eTicket = DES.encrypt(IOTKEY[:8], ticket) eticket_str = base64.b64encode(eTicket).decode("utf-8") payload = '{{"sessionkey":"{}","timestamp":"{}","lifetime":"{}","ticket":"{}"}}'.format( key, timestampStr, life, eticket_str) client_key = base64.b64decode(password) cipher = DES.encrypt(client_key[48:56], payload) salt = base64.b64encode(client_key[:32]).decode("utf-8") return_packet = '{{"salt":"{}","payload":"{}"}}'.format( salt, base64.b64encode(cipher).decode("utf-8")) return return_packet.encode()
def main(): TCP_IP = '127.0.0.1' SERV_PORT = 5005 BOB_PORT = 5004 ALICE_PORT = 5003 BUFFER_SIZE = 4096 #connect to KDC to establish aliceKey servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servSock.connect((TCP_IP, SERV_PORT)) #clients are aware of each others' usernames alice = "Alice" bob = "Bob" servSock.send(alice.encode("utf-8")) aliceKey = diffieHellman(servSock, False) aliceNonce = generate_nonce() namePrint(alice, "aliceKey established with server as " + str(aliceKey)) #connect to Bob to start exchanging information bobSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bobSock.connect((TCP_IP, BOB_PORT)) #1. Alice sends a request to Bob namePrint(alice, "step 1: request to Bob") msg = [alice] sendMessage(bobSock, msg) #3. Alice sends a message to the server identifying herself and Bob, telling the server she wants to communicate with Bob. namePrint(alice, "step 3: request to Server") encryptedMsg = receiveMessage(bobSock) msg = [alice, bob, aliceNonce, encryptedMsg] sendMessage(servSock, msg) #5. Alice forwards the key to Bob who can decrypt it with the key he shares with the server, thus authenticating the data. namePrint(alice, "step 5: pass Server response to Bob") encryptedNewMsg = receiveMessage(servSock) decryptedServerMsg = DES.frombits(DES.decrypt(encryptedNewMsg, aliceKey)) serverMsg = decoder.decode(decryptedServerMsg) aliceKab = serverMsg[2] toBob = serverMsg[3] sendMessage(bobSock, toBob) #7. Alice performs a simple operation on the nonce, re-encrypts it and sends it back verifying that she is still alive and that she holds the key. namePrint(alice, "step 7: send nonce operation result to Bob") encryptedNewMsg = receiveMessage(bobSock) decryptedBobMsg = DES.frombits(DES.decrypt(encryptedNewMsg, aliceKab)) decryptedBob = decoder.decode(decryptedBobMsg) newMsg = [nonceSubtract(decryptedBob[0])] encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)), aliceKab) sendMessage(bobSock, encryptedNewMsg) #time too chat! namePrint(alice, "Success! Time to chat!") threading.Thread(target=chatDataHandler, args=(bobSock, bob, aliceKab)).start() while (True): sendMessage( bobSock, DES.encrypt(DES.tobits(encoder.encode(input(""))), aliceKab))
def main(): TCP_IP = '127.0.0.1' SERV_PORT = 5005 BUFFER_SIZE = 4096 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, SERV_PORT)) s.listen(1) names = [] keys = [] for i in range(2): print( "Server: Awaiting {0} connection to establish diffie-hellman key.." .format("first" if i == 0 else "second")) conn, addr = s.accept() names.append(conn.recv(BUFFER_SIZE).decode("utf-8")) print( "Server: Connected to {0}. Running diffieHellman for initial key.". format(names[i])) keys.append(diffieHellman(conn, True)) print("Server: server key for {0}: {1}".format(names[i], keys[i])) if (i == 0): #close Bob's connection, but keep Alice open for a bit longer conn.close() bobKey = keys[0] aliceKey = keys[1] #generate random session key on the server for alice and bob to communicate Kab = [random.randint(0, 1) for _ in range(10)] #4. The server generates K_AB and sends back to Alice a copy encrypted under K_BS for Alice to forward to Bob and also a copy for Alice. #Since Alice may be requesting keys for several different people, the nonce assures Alice that the message is fresh and that #the server is replying to that particular message and the inclusion of Bob's name tells Alice who she is to share this key with. #Note the inclusion of the nonce. print( "Server: step 4: generate K_AB and send double encrypted message to Alice" ) msg = receiveMessage(conn) decryptedBobMsg = DES.frombits(DES.decrypt(msg[3], bobKey)) decryptedBob = decoder.decode(decryptedBobMsg) decryptedBob.append(Kab) reEncryptedBob = DES.encrypt(DES.tobits(encoder.encode(decryptedBob)), bobKey) newMsg = [msg[1], msg[2], Kab, reEncryptedBob] encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)), aliceKey) sendMessage(conn, encryptedNewMsg) conn.close() input("Server: My part is done. Press enter to exit...")
def ss_server(tgs_ans): time = datetime.datetime.now().timestamp() info = { 'tgs': tgs_ans['tgs'], 'auth': DES.encrypt(str({ 'c': __client, 'time': time }), tgs_ans['key']) } print('\n\tRequest to SS_server:') print(info) res_encr = SS_server(info) print('\n\tSS_server encrypted response:') print(res_encr) res = eval(DES.decrypt(res_encr, tgs_ans['key'])) print('\n\tSS_server decrypted response:') print(res) if abs(res - time - 1) > 1e-6: raise ValueError("Not connected") print('\n\nOK. Connected')
def tgs_server(auth): info = { 'tgt': auth['tgt'], 'auth': DES.encrypt( str({ 'c': __client, 'time': datetime.datetime.now().timestamp() }), auth['key']), 'id': __target } print('\n\tRequest to TGS_server:') print(info) res_encr = TGS_server(info) print('\n\tTGS_server encrypted response:') print(res_encr) res = DES.decrypt(res_encr, auth['key']) print('\n\tTGS_server decrypted response:') print(res) return eval(res)
def mac(m, k): #given message and key, create a mac code #go through m in 8 bit blocks i = 0 j = 8 d = m[i:j] #encrypt block #IV= 0 so there is no need to xor with IV, answer will be the same o = DES.encrypt(d, k) while j != len(m): i = i + 8 j = j + 8 #xor previosly encrypted block w plaintext d = DES.xor(o, m[i:j]) #encrypt newly xord block o = DES.encrypt(d, k) return o
def main(): des = DES() Des_IV = "Passw0rd" encode = des.encrypt("Passw0rd", Des_IV, str("Hello World!")) encode2 = des.decrypt("Passw0rd", Des_IV, str("53c8927a4dd1e9b6f44c9d53af92c794")) print(encode) print(encode2)
def AS_server(c_id: str): if c_id not in database.clients: return {} k_c = database.clients[c_id] tgs_id = database.tgs_id k_c_tgc = database.keys[(c_id, tgs_id)] tgt = { 'c': c_id, 'tgs': tgs_id, 'time': datetime.datetime.now().timestamp(), 'period': 1000, 'key': k_c_tgc } res = { 'tgt': DES.encrypt(str(tgt), database.K_as_tgs), 'key': k_c_tgc } return DES.encrypt(str(res), k_c)
def generate_authenticator(ticket, username, servername, command, logout): global i dateTimeObj = datetime.now() timestampStr = dateTimeObj.strftime("%Y-%m-%d %H:%M:%S.%f") authenticator = '{{"username":"******","timestamp":"{}","logout":"{}"}}'.format( username, timestampStr, str(logout)) sessionkey = base64.b64decode(ticket["sessionkey"]) e_authenticator = DES.encrypt(sessionkey[16:24], authenticator) e_authenticator_str = base64.b64encode(e_authenticator).decode("utf-8") message = sign(command) i += 1 print(i, message) payload = '{{"command":"{}","server":"{}","ticket":"{}","authenticator":"{}"}}'.format( message, servername, ticket["ticket"], e_authenticator_str) return payload.encode()
def SS_server(info): auth_encr = info['auth'] tgs_encr = info['tgs'] key_tgs_ss = database.keys[(__server, __tgs)] tgs = DES.decrypt(tgs_encr, key_tgs_ss) tgs = eval(tgs) key_c_ss = tgs['key'] auth = DES.decrypt(auth_encr, key_c_ss) auth = eval(auth) if auth['c'] != tgs['c']: raise ValueError('Clients not equal') if auth['time'] - tgs['time'] > tgs['period']: raise ValueError('Period is not valid') response = auth['time'] + 1 return DES.encrypt(str(response), key_c_ss)
def encryptor(): # 明文: plain = read_str("明文") # 生成密钥: key = keygen() k = key["bin"] print("Your key: ", key["hex"]) # 编码: b = encode(plain) print('encoding: ', b) # 裁剪: encrypt_package = cut(b, 64) print("Your additional bits count: ", encrypt_package["addition_count"]) cipher = "" for d in encrypt_package["data"]: node = DES.encrypt(d, k, silence=True) cipher += node print('密文: ' + _2hex(cipher)) print('复制以下内容以解密:') print( _2hex(cipher) + ' ' + str(encrypt_package["addition_count"]) + ' ' + key["hex"])
def main(): host = '127.0.0.1' port = 4500 # start out with the key, CHANGE KEY HERE key10bit = '1010101010' k1, k2 = DES.generateKeys(key10bit) # bind the socket to host and port mySocket = socket.socket() # client does not need to bind, just connect! mySocket.connect((host,port)) plain_text = input("Type a to start and q to quit:") # keep reading in data till user quits while plain_text != 'q': mySocket.send(plain_text.encode()) data = mySocket.recv(1024).decode() print ('Received from server: ' + data) plain_text = (input("Enter a 8 bit plain text => ")) # unless they want to quit (which would bork up my function as of now), encrypt! if(plain_text.lower()=='q'): continue # if it is not a 8bit, keep asking for somethin while(len(plain_text)!=8): plain_text = (input("Must enter a 8 bit plain text => ")) # encrypt and send! cipher_text = DES.encrypt(plain_text, k1, k2) print("Sending encrpted message to server:", cipher_text) plain_text = cipher_text mySocket.close()
from DES import * myDES = DES(); plaintext = '0123456789ABCDEF'; key = '133457799BBCDFF1'; ciphertext = myDES.encrypt(plaintext, key) decrypted = myDES.decrypt(ciphertext,key) print('##########') print('key = ' + key ) print('ciphertext = ' + ciphertext) print('plaintext = ' + plaintext ) print('decrypted = ' + decrypted )
def main(): TCP_IP = '127.0.0.1' SERV_PORT = 5005 BOB_PORT = 5004 BUFFER_SIZE = 4096 #connect to KDC to establish bobKey s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, SERV_PORT)) #clients are aware of each others' usernames alice = "Alice" bob = "Bob" s.send(bob.encode("utf-8")) bobKey = diffieHellman(s, False) s.close() bobNonce = generate_nonce() bobNoncePrime = generate_nonce() namePrint(bob,"bobKey established with server as " + str(bobKey)) #prepare for a connection from Alice s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, BOB_PORT)) s.listen(1) conn, addr = s.accept() #2. Bob responds with a nonce encrypted under his key with the Server namePrint(bob,"step 2: send Alice noncePrime") msg = receiveMessage(conn) msg.append(bobNoncePrime) encryptedMsg = DES.encrypt(DES.tobits(encoder.encode(msg)),bobKey) sendMessage(conn, encryptedMsg) #6. Bob sends Alice a nonce encrypted under K_AB to show that he has the key. namePrint(bob,"step 6: send Alice nonce encrypted under K_AB") toBob = receiveMessage(conn) decryptedAliceMsg = DES.frombits(DES.decrypt(toBob,bobKey)) decryptedAlice = decoder.decode(decryptedAliceMsg) #verify that bobNoncePrime made it back if (decryptedAlice[1] != bobNoncePrime): namePrint(bob,"Error: Bob Nonce Prime has been corrupted! Aborting in case of attack.") sys.exit() bobKab = decryptedAlice[2] newMsg = [bobNonce] encryptedNewMsg = DES.encrypt(DES.tobits(encoder.encode(newMsg)),bobKab) sendMessage(conn, encryptedNewMsg) #8. Bob see's that Alice's computation was correct. Hurray, we're ready to chat! namePrint(bob,"step 8: verify Alice nonce operation result") encryptedNewMsg = receiveMessage(conn) decryptedAliceMsg = DES.frombits(DES.decrypt(encryptedNewMsg,bobKab)) decryptedAlice = decoder.decode(decryptedAliceMsg) if (decryptedAlice[0] == nonceSubtract(bobNonce)): namePrint(bob,"Success! Time to chat!") else: namePrint(bob,"Error: Did not receive Bob Nonce - 1 from Alice") sys.exit() #time to chat! threading.Thread(target=chatDataHandler, args = (conn, alice, bobKab)).start() while (True): sendMessage(conn,DES.encrypt(DES.tobits(encoder.encode(input(""))),bobKab))
import DES as des import binascii import os import sys text = des.encrypt('0123456789ABCDEF', '133457799BBCDFF1', False) print(text) result = des.decrypt(text, '133457799BBCDFF1') print(result) #print(bin(int('123', 16))[2:].zfill(12)) #decrypted = des.decrypt(text, 'EAB234CA5B2D3572') #print(decrypted) #bits = '1011' #temp = '1111' #temp = int(temp, 2) #bits = int(bits, 2) #fillBits = int(bin(bits >> 3)[2:].zfill(4),2) #leftShift = int(bin(temp & bits << 1)[2:].zfill(4),2) #result = bin((temp & bits << 1) | int(bin((bits >> (3)))[2:].zfill(4), 2))[2:] #result = bin((temp & (bits << 1)) | int(bin((bits >> (4 - 1)))[2:].zfill(4), 2))[2:] #print(leftShift) #print(fillBits) #print(bin(leftShift | fillBits)[2:].zfill(4))