def create_enc(salt, r): plaintext = random.getrandbits(plaintext_len) debug("Plaintext: %s" % get_hex(random.long_to_bytes(plaintext))) # 32 length key #salt = random.getrandbits(plaintext_len) key = get_key_from_data(random.long_to_bytes(salt) + get_location(r)) aes = AES.new(key) enc = aes.encrypt(random.long_to_bytes(plaintext)) debug("Encrypted: %s" % get_hex(enc)) return (plaintext, enc)
def create_enc(salt, r): plaintext = random.getrandbits( plaintext_len ) debug( "Plaintext: %s" %get_hex( random.long_to_bytes(plaintext) )) # 32 length key #salt = random.getrandbits(plaintext_len) key = get_key_from_data( random.long_to_bytes(salt) + get_location(r) ) aes = AES.new( key ) enc = aes.encrypt( random.long_to_bytes(plaintext) ) debug( "Encrypted: %s" % get_hex(enc) ) return (plaintext, enc)
def gen_tag(block, key, hash_func=SHA256): """generate a tag for 'block' with 'key', return the tag in bytes key -- cryptografic key hash_func -- hash algorithm """ key = random.long_to_bytes(key) Mac = HMAC.new(key, block, hash_func) tag = Mac.digest() return tag
def __init__(self, sought_id, server_nonce): # XXX TODO: possibly we should enforce constraints on the length # and structure of the server nonce (e.g. it must be exactly 32 # lowercase hex digits or we won't respond). self.server_nonce = server_nonce self.sought_id = sought_id self.nonce = random.long_to_bytes(random.getrandbits(256)).encode("hex") # XXX TODO: we should find the private key immediately when the # responder object is created (if only we knew where to look for # it!) -- equivalent to calling self.find_priv() with an appropriate # list of candidate files. self.privkey = None
def send_info(file_name, key, blocksize, cloud_ip, server_sock): """ send the file name and key which generate tags to LC; 128 bytes for file name, 4 bytes for key-length, 32 bytes for key 4 bytes for blocksize, and 4 bytes for cloud ip address file_name -- name of the file key -- the key mentioned above server_sock -- socket """ key_inbytes = random.long_to_bytes(key) key_len = len(key_inbytes) file_name = struct.pack('128s', file_name) server_sock.send(file_name) server_sock.send(uint2str(key_len)) server_sock.send(key_inbytes) server_sock.send(uint2str(blocksize)) server_sock.send(ip2net(cloud_ip))
def generate_pad(length): ''' Generate a one- time pad using pycrypto.random Arguments ----------- length: int, length of pad Returns ---------- pad: (length,) dtype_pad random data unused: (length,) bool, unused charecters in pad ''' # get random bits and convert them into a numpy array pad = np.fromstring(random.long_to_bytes( random.getrandbits(int(length * 8))), dtype=dtype_pad) unused = np.ones(len(pad), dtype=np.bool) return pad, unused
def verify_proof(blocksize, key, hash_func = SHA256): """landmark verifies whether the proof from cloud is True return True or False blocksize -- size of block key -- key used to generating proof(MAC) hash_func -- hash function """ i, size = 0, blocksize + 4 key = random.long_to_bytes(key) for pair in index_tag: temp = proof[i*size : (i+1)*size] index = str2uint(temp[:4]) block = temp[4:] if pair[0] != index: # verify index first print 'Index not match!' return False else: Mac = HMAC.new(key, block, hash_func) tag = Mac.digest() if tag != pair[1]: # verify tag second print 'Bad block!' return False i += 1 return True
def test_invalid_decrypt(self): s = long_to_bytes(randrange(2**1024)) secret = self.public_key.encrypt(s) with self.assertRaises(Exception): self.private_key.decrypt(secret[:-1])
def test_encrypt_and_decrypt(self): s = long_to_bytes(randrange(2**1024)) secret = self.public_key.encrypt(s) length = len(s) self.assertEquals(s, self.private_key.decrypt(secret)[:length])
def wait_connection(): global s global tstart global tend global user global salts while 1: data = s.recv(1024) (dest_user, mtype, emessage) = ast.literal_eval(data) if mtype == SALT: print "Received salt: ", get_hex(random.long_to_bytes(emessage)) salts[dest_user] = emessage elif mtype == FIRST_STEP: [r, enc_message] = emessage key = get_key_from_data( random.long_to_bytes(salts[dest_user]) + get_location(r)) aes = AES.new(key) message = aes.decrypt(enc_message) del salts[dest_user] debug("Decrypted: %s" % get_hex(message)) new_key = SHA256.new(message).digest() debug("New key: %s" % get_hex(new_key)) new_plaintext = random.getrandbits(plaintext_len) debug("New plaintext: %s" % get_hex(random.long_to_bytes(new_plaintext))) aes = AES.new(new_key) enc = aes.encrypt(random.long_to_bytes(new_plaintext)) debug("New Encrypted: %s" % get_hex(enc)) message = [dest_user, enc, random.long_to_bytes(new_plaintext)] s.sendall(str((user, SECOND_STEP, message))) elif mtype == SECOND_STEP: del salts[dest_user] aes = AES.new(user_dict[dest_user]) debug("Received text to decrypt: %s" % get_hex(emessage)) result = aes.decrypt(emessage) debug("Decoded: %s" % get_hex(result)) message = [dest_user, result] s.sendall(str((user, FINAL, message))) elif mtype == FINAL: tend = datetime.now() print tend - tstart print "I am user %s " % user if emessage == ARE_CLOSE: print "User %s is somewhere nearby." % dest_user elif emessage == DISTANT: print "User %s is at an unknown location." % dest_user else: print "Error in message received." return
def randbytes(k): return random.long_to_bytes(random.getrandbits(8*k))
def make_challenge(pem_data): """Create a proof-of-possession challenge for a particular public key. (The caller must verify that pem_data is a valid RSA public key.)""" server_nonce = random.long_to_bytes(random.getrandbits(256)).encode("hex") return keyid(pem_data), server_nonce
sport = dport = None # nope pkt.data.src, pkt.data.dst = mangleIPs( pkt.data.src, pkt.data.dst, sport, dport) pktdata = str(pkt) except Exception, e: print e out.write(len(pktdata), pktdata, ts) if __name__ == '__main__': global key, init_ts, start_ts, replace_ts, by_flow, anon_mac, zero_mac, exclude, exclude_port, anon_all, ip_range, ip_mask opts, args = getopts(sys.argv[1:], 'i:aezftx:p:rk:', [ 'ip=', 'all', 'ether', 'zero', 'flow', 'ts', 'exclude=', 'random', 'key=', 'port='], ['-x', '--exclude', '-p', '--port']) if '-r' in opts or '--random' in opts: key = random.long_to_bytes(random.getrandbits(64), 8) else: key = '' key = opts.get('-k', opts.get('--key', key)) ip_range = opts.get('-i', opts.get('--ip', '0.0.0.0')) ip_mask = 0 # bitmask for hashed address ipr = '' for o in map(int, ip_range.split('.')): ipr += chr(o) ip_mask <<= 8 # shift by 8 bits if not o: ip_mask |= 0xff # set octet mask to 0xff if ip_range octet is zero ip_range = iptoint(ipr) # convert to int value for hash&mask|ip_range replace_ts = '-t' in opts or '--ts' in opts
def wait_connection(): global s global tstart global tend global user global salts while 1: data = s.recv(1024) (dest_user, mtype, emessage) = ast.literal_eval(data) if mtype == SALT: print "Received salt: ", get_hex(random.long_to_bytes(emessage)) salts[dest_user] = emessage elif mtype == FIRST_STEP: [r, enc_message] = emessage key = get_key_from_data( random.long_to_bytes(salts[dest_user]) + get_location(r) ) aes = AES.new( key ) message = aes.decrypt(enc_message) del salts[dest_user] debug( "Decrypted: %s" % get_hex( message ) ) new_key = SHA256.new( message ).digest() debug( "New key: %s" %get_hex(new_key) ) new_plaintext = random.getrandbits( plaintext_len ) debug("New plaintext: %s" % get_hex( random.long_to_bytes(new_plaintext) ) ) aes = AES.new( new_key ) enc = aes.encrypt(random.long_to_bytes(new_plaintext)) debug( "New Encrypted: %s" % get_hex(enc) ) message = [ dest_user, enc, random.long_to_bytes(new_plaintext) ] s.sendall( str( (user, SECOND_STEP, message) )) elif mtype == SECOND_STEP: del salts[dest_user] aes = AES.new( user_dict[dest_user] ) debug( "Received text to decrypt: %s" %get_hex(emessage) ) result = aes.decrypt(emessage) debug( "Decoded: %s" %get_hex(result) ) message = [ dest_user, result ] s.sendall( str( (user, FINAL, message)) ) elif mtype == FINAL: tend = datetime.now() print tend - tstart print "I am user %s " %user if emessage == ARE_CLOSE: print "User %s is somewhere nearby." %dest_user elif emessage == DISTANT: print "User %s is at an unknown location." %dest_user else: print "Error in message received." return
def store_key(key, file_name): """ store the key in file named 'file_name' """ with open(file_name, 'wb') as fp: for item in key: fp.write(random.long_to_bytes(item))
pkt.src=mangleMAC(pkt.src) pkt.dst=mangleMAC(pkt.dst) if pkt.type==dpkt.ethernet.ETH_TYPE_IP: try: sport,dport=pkt.data.data.sport,pkt.data.data.dport #TCP or UDP? except: sport=dport=None #nope pkt.data.src,pkt.data.dst=mangleIPs(pkt.data.src,pkt.data.dst,sport,dport) pktdata=str(pkt) except Exception,e: print e out.write(len(pktdata),pktdata,ts) if __name__ == '__main__': global key,init_ts,start_ts,replace_ts,by_flow,anon_mac,zero_mac,exclude,exclude_port,anon_all,ip_range,ip_mask opts,args=getopts(sys.argv[1:],'i:aezftx:p:rk:',['ip=','all','ether','zero','flow','ts','exclude=','random','key=','port='],['-x','--exclude','-p','--port']) if '-r' in opts or '--random' in opts: key=random.long_to_bytes(random.getrandbits(64),8) else: key='' key=opts.get('-k',opts.get('--key',key)) ip_range=opts.get('-i',opts.get('--ip','0.0.0.0')) ip_mask=0 #bitmask for hashed address ipr='' for o in map(int,ip_range.split('.')): ipr+=chr(o) ip_mask<<=8 #shift by 8 bits if not o: ip_mask|=0xff #set octet mask to 0xff if ip_range octet is zero ip_range=iptoint(ipr) #convert to int value for hash&mask|ip_range replace_ts='-t' in opts or '--ts' in opts by_flow='-f' in opts or '--flow' in opts anon_mac='-e' in opts or '--ether' in opts
def main(): global tstart global tend signal.signal(signal.SIGINT, signal_handler) global s global user_dict global user global location global distance user = raw_input("Enter your username: "******"Enter your location: ") try: x = float(location.split(",")[0]) y = float(location.split(",")[1]) break except: print "[ERR] Formatul trebuie sa fie de forma: X,Y" print "[ERR] Unde X si Y sunt coordonate geografice" continue s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall(str((user, USER_REG, ""))) t = threading.Thread(target=wait_connection, args=()) t.daemon = True t.start() distance = int(raw_input("Distanta de cautare: ")) while 1: dest_user = raw_input("Trimite catre user: ") tstart = datetime.now() if dest_user: s.sendall(str((user, GET_SALT, dest_user))) while dest_user not in salts: time.sleep(0.5) (plaintext, enc) = create_enc(salts[dest_user], distance) user_dict[dest_user] = get_key_from_data( random.long_to_bytes(plaintext)) message = [dest_user, distance, enc] s.sendall(str((user, FWD_TO, message))) continue signal.pause()
pktdata = str(pkt) except Exception, e: print e out.write(len(pktdata), pktdata, ts) if __name__ == '__main__': global key, init_ts, start_ts, replace_ts, by_flow, anon_mac, zero_mac, exclude, exclude_port, anon_all, ip_range, ip_mask opts, args = getopts(sys.argv[1:], 'i:aezftx:p:rk:', [ 'ip=', 'all', 'ether', 'zero', 'flow', 'ts', 'exclude=', 'random', 'key=', 'port=' ], ['-x', '--exclude', '-p', '--port']) if '-r' in opts or '--random' in opts: key = random.long_to_bytes(random.getrandbits(64), 8) else: key = '' key = opts.get('-k', opts.get('--key', key)) ip_range = opts.get('-i', opts.get('--ip', '0.0.0.0')) ip_mask = 0 # bitmask for hashed address ipr = '' for o in map(int, ip_range.split('.')): ipr += chr(o) ip_mask <<= 8 # shift by 8 bits if not o: ip_mask |= 0xff # set octet mask to 0xff if ip_range octet is zero ip_range = iptoint(ipr) # convert to int value for hash&mask|ip_range replace_ts = '-t' in opts or '--ts' in opts
def main(): global tstart global tend signal.signal(signal.SIGINT, signal_handler) global s global user_dict global user global location global distance user = raw_input("Enter your username: "******"Enter your location: ") try: x = float(location.split(",")[0]) y = float(location.split(",")[1]) break except: print "[ERR] Formatul trebuie sa fie de forma: X,Y" print "[ERR] Unde X si Y sunt coordonate geografice" continue s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall( str( (user, USER_REG, "") ) ) t = threading.Thread(target=wait_connection, args = ( ) ) t.daemon=True t.start() distance = int( raw_input("Distanta de cautare: ") ) while 1: dest_user = raw_input("Trimite catre user: ") tstart = datetime.now() if dest_user: s.sendall( str((user, GET_SALT, dest_user))) while dest_user not in salts: time.sleep(0.5) (plaintext, enc) = create_enc( salts[dest_user], distance) user_dict[ dest_user ] = get_key_from_data( random.long_to_bytes(plaintext) ) message = [dest_user, distance, enc] s.sendall( str( (user, FWD_TO, message) ) ) continue signal.pause()