def readEncJSON(key): with open('config.cg', 'r') as json_file: crypter = objcrypt.Crypter(key, 'cbc') str_json = json_file.read() data = crypter.decrypt_json(str_json) dec_json = json.loads(data) return dec_json['config']
def writeEncJSON(key): data = {} with open('config.cg', 'w') as outfile: crypter = objcrypt.Crypter(key, 'cbc') json_file = json.dumps(data, ensure_ascii=False) enc_json = crypter.encrypt_json(json_file) outfile.write(enc_json) outfile.close()
def receive_data(): url = "http://10.0.2.5:8000/sendcs/" data = {'ipaddress': get_primary_ip()} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) with open("passkey.txt", "r") as f: passkey = f.read() crypter = objcrypt.Crypter(passkey, 'cbc') print(str(r.text)) dec_json = crypter.decrypt_json(r.text) print(str(dec_json)) if (str(r.text) != "no-credentials"): with open('data.json', 'w') as f: f.write(dec_json) else: if os.path.exists("data.json"): os.remove("data.json")
def sendcs(request): if request.method == "POST": received = json.loads(request.body.decode("utf-8")) ipaddress = received['ipaddress'] print('ipaddress: %s' % ipaddress) filename = ipaddress + "/passkey.txt" with open(filename, "r") as f: passkey = f.read() print(str(passkey)) try: cd = cred.objects.get(ipaddress=ipaddress) cre = {"username": cd.username, "password": cd.password} cred_json = json.dumps(cre) crypter = objcrypt.Crypter(str(passkey), 'cbc') enc_json = crypter.encrypt_json(cred_json) return HttpResponse(enc_json) except cred.DoesNotExist: return HttpResponse('no-credentials') return HttpResponse('')
import objcrypt, json, time dictionary = {'test': 'test value', 'test1': 'test1 value1'} print( 'Values may change but the Key Test shows that hardcoded dictionary will always be able to be decrypted with the same key.' ) time.sleep(5) print('Python Object:\n', dictionary) print() encrypter = objcrypt.Crypter('test', 'cbc') print('Python Obj Encryption'.center(45, '-')) enc_dict = encrypter.encrypt_object(dictionary) print(enc_dict) dec_dict = encrypter.decrypt_object(enc_dict) print(dec_dict) print() print('JSON Encryption'.center(45, '-')) json_dict = json.dumps(dictionary) print('JSON Object:\n', json_dict) print() enc_j = encrypter.encrypt_json(json_dict) print(enc_j) dec_j = encrypter.decrypt_json(enc_j) print(dec_j) enc_dict = { 'test': '56hBuGghCcWW0r2MkHmzOzCfYr9HaLRQhIelPoCVqcPDvmNkmsRkQSIJblW22Yq9', 'test1': '4pVnXMOf3SvYlAc2ZuTJw9ql7tZcJjYWWfwnhseZitWRq+EzZ1Hog6/i0NOoW5Fe' } print() print('Key Test'.center(45, '-')) test = encrypter.decrypt_object(enc_dict)
def server_program(): # get the hostname host = socket.gethostname() port = 5000 # initiate port no above 1024 server_socket = socket.socket() # get instance # look closely. The bind() function takes tuple as argument server_socket.bind((host, port)) # bind host address and port together # configure how many client the server can listen simultaneously server_socket.listen(5) #conn, address = server_socket.accept() # accept new connection #print("Connection from: " + str(address)) #print("Enter 'quit' to exit") #message = input(" -> ") while True: conn, address = server_socket.accept() print("Connection from: " + str(address)) code = conn.recv(1024).decode() if code == str(1): print("Entering New Record creation") # receive data stream. it won't accept data packet greater than 1024 bytes jsonpath = "json_files" name = conn.recv(1024).decode() gender = conn.recv(1024).decode() dob = conn.recv(1024).decode() aadhar = conn.recv(1024).decode() print("from connected user:name, gender, dob, aadhar\n ") print(name, gender, dob, aadhar) date = datetime.now() data_entered = {} data_entered["Name"] = name data_entered["Gender"] = gender data_entered["DOB"] = dob data_entered["AADHAR"] = aadhar data_entered["Timestamp"] = str(date) #data_entered["ImagePath"]=str("./"+image_path) datastring = "" ######################################################## password = randomString() key = password crypter = objcrypt.Crypter('key', password) ######################################################## count = 0 name_d = {} aadharno = [] result = newuser(data_entered, count, aadharno, server_socket, key) conn.send(result.encode()) ######################################################### print("Doing encryption of json") print("Encryption key generated:" + str(password)) bufferSize = 64 * 1024 # encrypt pyAesCrypt.encryptFile( jsonpath + "/" + name + result + ".json", jsonpath + "/" + name + result + ".json.aes", password, bufferSize) # decrypt #pyAesCrypt.decryptFile("data.txt.aes", "dataout.txt", password, bufferSize)jsonpath+"/"+name+result+".json.aes" print("Done encryption!") x = open(jsonpath + "/" + name + result + ".json.aes", "rb") while 1: data = x.read(1024) if data == b'': #print("finished sending") x.close() break conn.send(data) x.close() print("Json sent") #exitval = conn.recv(1024).decode() #if exitval=="done": ######################################################### #time.sleep(10) #break #files = glob.glob(jsonpath+"/") #for f in files: # os.remove(f) else: print("Entering view mode") value = conn.recv(1024).decode() #print(value) hashvalue = conn.recv(1024).decode() #print(hashvalue) print("Hash of block from clien:", hashvalue) if value == "True": f = open("hashcode.json", "r") di = json.load(f) decrypt_key = di[hashvalue] print("Sending the decrypted key:", decrypt_key) conn.send(decrypt_key.encode()) else: print("Theft") n = input(" Press 1 to Turn off, 0 to continue") if n == str(1): break conn.close()
def main(args): start = time.time() #name = args.get("params", "stranger") name = "stranger" prefixNum = 0 numIpFiles = 1000 numKeys = 1 numChunks = 1 if (name != "stranger"): messagesArr = json.dumps(name) msg = json.loads(messagesArr) print("\t msg: %s " % (str(msg))) bucketName = msg["bucketName"] numKeys = msg["numKeys"] numChunks = msg["numChunks"] else: bucketName = "ow-aws-fe" numKeys = 5 numChunks = 5 prefixNum = random.randrange(1, numIpFiles) if (numKeys < 0): numKeys = 1 if (numChunks < 0): numChunks = 1 keyName = "data" + str(prefixNum) + ".p0" #return "Error: params not found!! name -->"+str(name) userDetails = { "user": "******", "access_key": access_key, "secret_key": secret_key, "host": host - ip, #bay16 "port": port - num, } access_key = userDetails["access_key"] secret_key = userDetails["secret_key"] hostname = userDetails["host"] portNum = userDetails["port"] bucketStr = hostname bucketStr = str(hostname) + ":" + str(portNum) + "\t" hosts = [{ "host": redis - host - 1, "port": "7000" }, { "host": redis - host - 2, "port": "7001" }, { "host": redis - host - 3, "port": "7002" }] startup_nodes = [hosts[random.randint(0, 2)]] #rc = rediscluster.StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True) rc = RedisCluster(startup_nodes=startup_nodes, decode_responses=True) tempFilename = "temp.log" encryptAccum = 0 dictionary = {} for idx in range(numKeys): prefixNum = random.randrange(0, numIpFiles - 1) keyName = "kv_" + str(prefixNum) + ".log" bucketStr = str(bucketName) + "\t " + str(keyName) # curObjKey = curBucket.get_key(keyName) # print ("\t idx: %d keyName: %s "%(idx,bucketStr)) # try: # curJsonObj = curObjKey.get_contents_to_filename(tempFilename) # except AttributeError: # return {"greeting": bucketStr} pullFileFromStorage(bucketName, keyName, tempFilename) tempDict = json.load(open(tempFilename)) dictLen = len(tempDict) sliceLen = dictLen // (numKeys) # should check numKeys? if (sliceLen < 1): sliceLen = 2 startIdx = idx * sliceLen endIdx = startIdx + (sliceLen // 2) tempArr = list(tempDict.keys()) print( "\t idx: %d sliceLen: %d len(tempArr): %d startIdx: %d endIdx: %d " % (idx, sliceLen, len(tempArr), startIdx, endIdx)) reqdItems = tempArr[startIdx:endIdx] for keyIdx, curKey in enumerate(reqdItems): newKey = str(curKey) + "_" + str(idx) #if(keyIdx%50==0): print ("\t keyIdx: %d curKey: %s newKey: %s "%(keyIdx,curKey,newKey)) dictionary[newKey] = tempDict[curKey] encryptBegin = time.time() crypter = objcrypt.Crypter('key', 'cbc') #dictionary = json.load(open(tempFilename)) encrypted_dict = crypter.encrypt_object(dictionary) dictStr = json.dumps(dictionary) enc_json = crypter.encrypt_json(dictStr) #json_dict) encryptEnd = time.time() encryptAccum = encryptAccum + (encryptEnd - encryptBegin) encLen = len(enc_json) print("\n\t len(dictionary): %d len(enc_json): %d " % (len(dictionary), len(enc_json))) for idx in range(numChunks): sliceLen = encLen // (numChunks) # should check numKeys? if (sliceLen < 1): sliceLen = 2 startIdx = idx * sliceLen endIdx = (idx + 1) * sliceLen - 1 slicedEncJson = enc_json[startIdx:endIdx] opFilenames = ["op.log"] opKeyName = "key" + str(random.randrange(0, 10000)) opKey = ["op_" + str(opKeyName) + ".log"] opFile = open(opFilenames[0], 'w') opFile.write(str(enc_json) + "\n") opFile.close() #writeEncryptedFile(curBucket,opKey,opFilenames) print( "\t len(dictionary): %d pushing opKey: %s len(slicedEncJson): %s " % (len(dictionary), opKeyName, len(slicedEncJson))) rc.set(opKeyName, enc_json) end = time.time() timeTaken = end - start encryptTime = encryptAccum #dbPush-encryptBegin bucketStr = str(bucketStr) + "\t time: " + str( '%.3f' % (timeTaken)) + "\t encryptTime: " + str('%.3f' % (encryptTime)) print("\t bucketStr: %s " % (bucketStr)) return {"greeting": bucketStr}
def __init__(self): from crowdsorting.settings.configurables import COOKIE_KEY self.crypter = objcrypt.Crypter(COOKIE_KEY, 'cbc')