def test_txt(): points = 0 try: encrypt_file("3240test1.txt",b"sixteenbytekey!!") with open("3240test1.txt.enc",'rb') as file: if contains_text("3240test1.txt","3240test1.txt.enc"): if debug: print("TEST 2: The encrypted file contained the unencrypted contents. -20 Points.\n ") points -= 20 except Exception as e: if debug: print("TEST 2: Exception " + type(e).__name__ + " during encryption. -20 Points.\n ") points -= 20 #Check for existence of decrypted file here? Run the decrypt in a different process to stop trickery? try: decrypt_file("3240test1.txt.enc",b"sixteenbytekey!!") if not hash_equal("3240test1.txt","DEC_3240test1.txt"): if debug: print("TEST 2: The decrypted file differs from the original. -10 Points.\n ") points -= 10 if not contains_text("3240test1.txt","DEC_3240test1.txt"): if debug: print("TEST 2: The differences between the files don't appear to be related to padding. -10 Points.\n ") points -= 10 except Exception as e: if debug: print("TEST 2: Exception " + type(e).__name__ + " during decryption. -20 Points.\n ") points -= 20 return points
def download_file(filename_ori, saveas=None): """ Download and decrypt the file. Output the file. Raise when filename_ori is not in filelist """ # Get the key, iv and tag from list record = None if filename_ori in filelist.mylist: record = filelist.mylist[filename_ori] r = download(record["filename_rand"]) elif filename_ori in filelist.mylist_share: record = filelist.mylist_share[filename_ori] r = download(record["filename_rand"], record["shared_by"]) else: log.print_error("error", "file '%s' not in record" % (filename_ori)) return False if saveas == None: outputfile = filename_ori else: outputfile = saveas # Try decryption try: encrypt.decrypt_file(outputfile, record["filename_rand"], record["key"], record["iv"], record["tag"]) except: log.print_error("error", "failed to decrypt '%s'" % (filename_ori)) return False return True
def test_bin(): try: encrypt_file("3240test2.jpg",b"sixteenbytekey!!") decrypt_file("3240test2.jpg.enc",b"sixteenbytekey!!") if not hash_equal("3240test2.jpg","DEC_3240test2.jpg"): if debug: print("TEST 4: The decrypted binary file differs from the original. -10 Points.\n ") return -10 except Exception as e: if debug: print("TEST 4: Exception " + type(e).__name__ + " during decryption. -10 Points.\n ") return -10 return 0
def decrypt_file_use_existing_key(): try: # Select encrypted file print("\nStep 1: Please select your encrypted file to decrypt : ") input("Press <ENTER> to continue...") try: encrypt_file = filedialog.askopenfile( initialdir="/", title="Select Encrypted File") print("The encrypted file you have selected is: " + encrypt_file.name) # Select a location to save the decrypted file print( "\nStep 2: Please select directory to save your decrypted file : " ) input("Press <ENTER> to continue...") decrypt_file = filedialog.asksaveasfile( initialdir="/", title="Save Decrypted File", filetypes=(("decrypt files", "*.dec"), ("all files", "*.*"))) x = decrypt_file.name except AttributeError: print("Operation cancelled by the user!") else: # Trim data from the path value decrypt_file = x.split('/')[-1] + ".dec" os.remove( x) # Exception handle: remove file without .dec extension print("You have saved the decrypted file as: " + decrypt_file) # Select a key file for decryption print("\nStep 3: Please select the Key File for decryption : ") input("Press <ENTER> to continue...") key_file = filedialog.askopenfile(initialdir="/", title="Select Key File") print("The key file you have selected to decrypt is: " + key_file.name) # Decryption process encrypt.decrypt_file(encrypt_file.name, decrypt_file, key_file.name) print("\nDecryption completed successfully and the decrypted '" + decrypt_file + "' file has created!") input("Press <ENTER> to continue...") except FileNotFoundError: print("Exception: File Not Found!")
def viewReport(): reportID = input("Enter the id of the report you would like to view: ") r = requests.post('http://127.0.0.1:8000/viewReport_FDA/', data={'reportID': reportID}) data = r.json() for key in data: print("report id: ", key) print("company name: ", data[key][0]) print("company phone: ", data[key][1]) print("ceo: ", data[key][2]) print("email: ", data[key][3]) print("location: ", data[key][4]) print("sector: ", data[key][5]) print("industry: ", data[key][6]) print("projects: ", data[key][7]) file = data[key][8] print("files: ", data[key][8]) print("file ids: ", data[key][9]) file_id = data[key][9] print("encrypted: ", data[key][10]) print() dl = input( "Would you like to download the files associated with this report? [y/n]: " ) if dl == 'y': #downloadFile(filename, reportID) print(file) for index in range(len(file)): file_name = file[index].split('/')[-1] url = "http://127.0.0.1:8000/download_file/" + str(file_id[index]) print(url) response = requests.get(url) # return response # url = "http://127.0.0.1:8000/" + file[0] # file_name = url.split('/')[-1] # print("Now downloading: ", file_name) # response = requests.get(url, stream=True) with open(file_name, 'wb') as f: for chunk in response.iter_content(chunk_size=127): if chunk: f.write(chunk) if data[key][10] == True: decrypt_file(file_name, '0123456789123456')
def test_keys(): try: encrypt_file("3240test1.txt",b"This is my key that's super long and oh my goodness it works so well") decrypt_file("3240test1.txt.enc",b"This is my key that's super long and oh my goodness it works so well") if not hash_equal("3240test1.txt","DEC_3240test1.txt"): if not contains_text("3240test1.txt","DEC_3240test1.txt"): if debug: print("TEST 5: Incorrectly decrypted with key of non-16 byte length. -10 Points.\n ") return -10 else: return 0 except Exception as e: if debug: print("TEST 5: Encountered exception " + type(e).__name__ + " with key of non-16 byte length. -10 Points.\n ") return -10 return 0
def test_block(): try: encrypt_file("3240test3.txt",b"sixteenbytekey!!") decrypt_file("3240test3.txt.enc",b"sixteenbytekey!!") if not hash_equal("3240test3.txt","DEC_3240test3.txt"): if not contains_text("3240test3.txt","DEC_3240test3.txt"): if debug: print("TEST 3: Incorrectly decrypted with a file of non-block size length. -10 Points.\n ") return -10 else: if debug: print("TEST 3: Failed to remove padding with a file of non-block size length. -5 Points.\n ") return -5 except Exception as e: if debug: print("TEST 3: Encountered exception " + type(e).__name__ + " with a file of non-block size length. -10 Points.\n ") return -10 return 0
def decrypt_file(self): filename = fdialog.askopenfilename() key = self.enter_key.get() self.t2.destroy() result = encrypt.decrypt_file(filename, key) if result: self.log["text"] = "Decryption was Successful" else: self.log["text"] = "An error has occured"
def decrypt_file(self): filename = fdialog.askopenfilename() key = self.enter_key.get() self.t2.destroy() result = encrypt.decrypt_file(filename, key) if result: self.log["text"]= "Decryption was Successful" else: self.log["text"]= "An error has occured"
def getdetail(path): log = [] try: r = client.get(detailurl(path)) a = r.json() except: # log.append(' (server error)'.ljust(30) + path) return log # print(a['path'],a['sha256'],a['isdir']) try: sha = None if not a['isdir']: data = bytes(a['docfile'], 'utf-8') sha = hashlib.sha256() sha.update(data) sha = sha.hexdigest() # data = base64.decodestring(data) data = a['docfile'] if sha == a['sha256']: assure_path_exists(observing_root + path) file = open(observing_root + path + '.enc', 'w') file.write(a['docfile']) file.close() decrypt_file(observing_root + path + '.enc') os.remove(observing_root + path + '.enc') # print(a['path'],'(downloaded)') log.append(' (downloaded)'.ljust(30) + path) else: log.append(' (failed (hash mismatch))'.ljust(30) + path) else: assure_path_exists(observing_root + a['path']) # print(a['path'],'(checked)') log.append(' (checked)'.ljust(30) + path) stamp = os.path.getmtime(observing_root + path) cur.execute('''DELETE FROM Files WHERE filepath="''' + path + '"') cur.execute( "INSERT INTO Files (filepath, sha256, stamp) VALUES (?,?,?)", [path, sha, str(stamp)]) except: # print(path,'(internal error)') log.append(' (internal error)'.ljust(30) + path) return log
def connect_to_github(access_token_path=access_token_path, password=access_token_pass, repository=repository): ''' Given an access token file, or an encrypted access token file and password, returns a Github connection, ''' hg = None if access_token_path.endswith('.enc'): access_token = encrypt.decrypt_file(access_token_path, password) else: with open(access_token_path, 'r') as token_file: access_token = token_file.readline() if len(access_token) == 40: hg = Github(access_token) else: exit(0) repo = hg.get_repo(repository) branch = repo.get_branch(branch='master') vprint(repo) vprint(branch) return hg, repo, branch
# command line decrypter from encrypt import decrypt_file import sys if len(sys.argv) == 3: decrypt_file(sys.argv[1], sys.argv[2]) elif len(sys.argv) == 4: decrypt_file(sys.argv[1], sys.argv[2], sys.argv[3]) else: print 'Usage: python decrypter.py [key] [input file] [output file]'
#coding:utf-8 import encrypt out_boot_path = "../Resources/boot.oxgame" out_game_path = "../Resources/game.bin" if __name__ == '__main__': encrypt.decrypt_file(out_boot_path) encrypt.decrypt_file(out_game_path) print("------- over --------")
def download(USER_NAME, USER_PATH, USER_PRK, args): #verigy command source = args[0] save_pos = args[1] if source[-1] == '/': source = source[:-1] if source[0:2] == './': source = source[2:] if not os.path.isdir(save_pos): info = 'no such destination directory' return False, info if source[0] == '/': source_path_split = source.split('/') if USER_NAME != source_path_split[1]: info = 'source directory permission denied' with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + USER_NAME + ':' + 'download ' + source) return False, info else: source_file = EFS_DIR + source[1:] else: source_file = EFS_DIR + USER_PATH + '/' + source if not os.path.isfile(source_file): info = 'no such source file' return False, info try: USER_PK, USER_PRK, USER_AES = _get_keys(USER_NAME, USER_PRK) except: info = 'get keys error' return False, info try: # get encrypted name en_file_name = encrypt.encrypt_filename(USER_PK, source_file) en_file_name = en_file_name.replace("/", r"_")[0:100] # download file os.system(PASS + 'scp ' + SERVER + en_file_name + ' ' + save_pos) source_split = source.split('/') filename = source_split[-1] os.rename(save_pos + '/' + en_file_name, save_pos + '/' + filename) except: info = 'download error' return False, info with open(save_pos + '/' + filename, 'r') as f: cipherfile = f.read() signature = cipherfile[0:344] cipherfile = cipherfile[344:] with open(save_pos + '/' + filename, 'w') as f: f.write(cipherfile) verify = encrypt.verify_sign(USER_PRK, signature, cipherfile) if not verify: info = 'the file has been modified illegally' os.remove(save_pos + '/' + filename) try: source_path = source_split[:-1] en_source = EFS_DIR + '/'.join(source_path) + '/' + en_file_name os.rename(source_file, en_source) os.system(PASS + 'scp ' + en_source + SERVER) os.rename(en_source, source_file) info = 'and the backup file has been uploaded, please read again' return False, info except: info = 'and fail to upload the backup file' return False, info else: try: # update backup with open(save_pos + '/' + filename, 'r') as f: cipherfile = f.read() with open(source_file, 'w') as f: f.write(cipherfile) plain = encrypt.decrypt_file(USER_AES, save_pos + '/' + filename) with open(save_pos + '/' + filename, 'w') as f: f.write(plain) info = 'succeed' return True, info except: info = 'decrypt error' return False, info
else: print "Reading data" #Config! BUCKET=ConfigSectionMap("AWS",Config)['bucket'] s3 = boto3.client( 's3', aws_access_key_id=ConfigSectionMap("AWS",Config)['access key'], aws_secret_access_key=ConfigSectionMap("AWS",Config)['secret access key'] ) # Getting the object: print("Getting S3 object and writing to file Recievedd...") # Note how we're using the same ``KEY`` we # created earlier. response = s3.get_object(Bucket=BUCKET, Key=hashhere, SSECustomerKey=key, SSECustomerAlgorithm='AES256') print("Done") f=open('Recievedd.enc','w') f.write(response['Body'].read()) f.close() encrypt.decrypt_file('Recievedd.enc',key) # Close the socket when done s.close print("The time that the server responded is %s" % tm.decode('ascii'))
def download(USER_NAME, USER_PATH, USER_PRK, USER_IP, SOCKET, ALL_SOCKET, LOCK_SOCKET, args): #verigy command source = args[0] save_pos = args[1] if source[-1] == '/': source = source[:-1] if source[0:2] == './': source = source[2:] if not os.path.isdir(save_pos): info = 'no such destination directory' return False, info if source[0] == '/': source_path_split = source.split('/') if USER_NAME != source_path_split[1]: info = 'source directory permission denied' with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + USER_NAME + ':' + 'download ' + source) return False, info else: source_file = EFS_DIR + source[1:] else: source_file = EFS_DIR + USER_PATH + '/' + source if not os.path.isfile(source_file): info = 'no such source file' return False, info _USER_PRK = USER_PRK try: USER_PK, USER_PRK, USER_AES = _get_keys(USER_NAME, USER_PRK) except: info = 'get keys error' return False, info try: # get encrypted name en_file_name = encrypt.encrypt_filename(USER_PK, source_file) en_file_name = en_file_name.replace("/", r"_")[0:100] # download file #os.system(PASS + 'scp ' + SERVER + en_file_name + ' ' + save_pos) _inquire(en_file_name, SOCKET, 0) DataNode = _get_datanode(SOCKET) #_upload_DataNode(USER_IP, cipherfile[0:16384], DataNode_1, 1, en_file_name) while _get_read_lock(LOCK_SOCKET, en_file_name) == 0: pass i = 1 cipherfile = '' while DataNode.has_key(str(i)): datanode_port = int(DataNode[str(i)][0]) data = str( _download_DataNode(en_file_name + '_' + str(i), datanode_port, ALL_SOCKET[datanode_port], int(i))) cipherfile = cipherfile + data i = i + 1 # if int(i) != len(cipherfile) / 16384 + 1: # _upload_DataNode(USER_IP, cipherfile[(int(i)-1)*16384:int(i)*16384], ALL_SOCKET[j], int(i), en_file_name+'_'+str(i), j) # else: # _upload_DataNode(USER_IP, cipherfile[(int(i)-1)*16384:len(cipherfile)], ALL_SOCKET[j], int(i), en_file_name+'_'+str(i), j) _release_read_lock(LOCK_SOCKET, en_file_name) source_split = source.split('/') filename = source_split[-1] # os.rename(save_pos + '/' + en_file_name, save_pos + '/' + filename) with open(save_pos + '/' + filename, 'wb') as f: f.write(cipherfile) except: info = 'download error' return False, info # with open(save_pos + '/' + filename, 'r') as f: # cipherfile = f.read() signature = cipherfile[0:344] cipherfile = cipherfile[344:] with open(save_pos + '/' + filename, 'w') as f: f.write(cipherfile) verify = encrypt.verify_sign(USER_PRK, signature, cipherfile) if not verify: info = 'the file has been modified illegally' os.remove(save_pos + '/' + filename) try: source_path = source_split[:-1] en_source = EFS_DIR + '/'.join(source_path) + '/' + en_file_name os.rename(source_file, en_source) #os.system(PASS + 'scp ' + en_source + SERVER) with open(en_source, 'w') as f: cipherfile = f.read() _inquire(en_file_name, SOCKET, len(cipherfile)) DataNode = _get_datanode(SOCKET) while _get_write_lock(LOCK_SOCKET, en_file_name) == 0: pass for i in DataNode.keys(): for j in DataNode[i]: if int(i) != len(cipherfile) / 16384 + 1: _upload_DataNode( USER_IP, cipherfile[(int(i) - 1) * 16384:int(i) * 16384], ALL_SOCKET[int(j)], int(i), en_file_name + '_' + str(i), int(j)) else: _upload_DataNode( USER_IP, cipherfile[(int(i) - 1) * 16384:len(cipherfile)], ALL_SOCKET[int(j)], int(i), en_file_name + '_' + str(i), int(j)) _release_write_lock(LOCK_SOCKET, en_file_name) os.rename(en_source, source_file) info = 'and the backup file has been uploaded, please read again' return False, info except: info = 'and fail to upload the backup file' return False, info else: try: # update backup with open(save_pos + '/' + filename, 'r') as f: cipherfile = f.read() with open(source_file, 'w') as f: f.write(cipherfile) plain = encrypt.decrypt_file(USER_AES, save_pos + '/' + filename) with open(save_pos + '/' + filename, 'w') as f: f.write(plain) info = 'succeed' return True, info except: info = 'decrypt error' return False, info
def download_file(self,dfile,report,user,password, private_key): import urllib if dfile == None: print("File does not exist") return print(dfile.url()) directory = os.path.expanduser("~/Desktop/"+report.title+"/") if not os.path.exists(directory): os.makedirs(directory) filename = ("http://gentle-shore-9521.herokuapp.com")+dfile.url()# Select your file here. with req.urlopen(filename) as response, open(directory+dfile.name(), 'wb') as out_file: shutil.copyfileobj(response, out_file) #try: # open encrypted file key = Keys.objects.get(username=report.user) print(report.user) print(key.private_key) print(0) private_key = RSA.importKey(key.private_key) print(1) #print((dfile.encrypted_symmetric_key[0])) #print(dfile.name(), dfile.encrypted_symmetric_key) decrypted_symmetric_key = private_key.decrypt(base64.b64decode(dfile.encrypted_symmetric_key)) #print(decrypted_symmetric_key) print(2) decrypted_symmetric_key = decrypted_symmetric_key.decode() print(3) #symmetric_key = SHA256.new(str(symmetric_key).encode()).hexdigest()[0:16] print(decrypted_symmetric_key) print(4) #print(dfile.name()) #print(dfile.image) #print(symmetric_key) plaintext = b'' #test = ProfileImage(image=dfile.image) #test.image.open(mode='rb') # with open(dfile,'rb') as fo: # # file = dfile.image.read() #print(type(dfile.image)) #file = dfile.image.read() #print(file) with open(directory+dfile.name(), 'rb') as fo: #print(fo) encrypted_text = fo.read() #print(encrypted_text) #print(5) file = encrypted_text #print(file) plaintext = decrypt_file(file, decrypted_symmetric_key) #print(plaintext) decrypted_text = encrypt.decrypt_file(encrypted_text, decrypted_symmetric_key) #print(decrypted_text) with open(directory+"asdf"+dfile.name(), 'wb') as fo: fo.write(plaintext) #except: # print("ERROR DURING DECRYPTION OF FILE") print("Downloaded to: " +os.path.expanduser("~/Desktop/"+report.title+"/"))
def download_share(USER_NAME, args): file_path = args[0] loc_RSA_1 = args[1] loc_RSA_2 = args[2] save_pos = args[3] if file_path[0] == '/': info = 'file name should be one of the listed results in "ls -s" in user/share/' return False, info share_path = '/' + USER_NAME + '/share/' + file_path with open(EFS_DIR + USER_NAME + '/share_mirror.json', 'r') as f: data = json.load(f) if share_path not in data.keys(): info = 'file name should be one of the listed results in "ls -s" in user/share/' return False, info share_mirror = data[share_path] group_name = share_mirror.split('/') filename = group_name[-1] group_name = group_name[1] real_path = EFS_DIR + str(share_mirror[1:]) with open(loc_RSA_1, 'r') as f: SHARE_RSA_1 = RSA.importKey(f.read()) with open(loc_RSA_2, 'r') as f: SHARE_RSA_2 = RSA.importKey(f.read()) with open(EFS_DIR + '/key/' + group_name + '_RSA_1.pem', 'r') as f: SHARE_PUBLIC_RSA_1 = RSA.importKey(f.read()) with open(EFS_DIR + '/key/' + group_name + '_RSA_2.pem', 'r') as f: SHARE_PUBLIC_RSA_2 = RSA.importKey(f.read()) with open(EFS_DIR + '/key/' + group_name + '_RSA_3.pem', 'r') as f: SHARE_PUBLIC_RSA_3 = RSA.importKey(f.read()) if not SHARE_RSA_1.decrypt(SHARE_PUBLIC_RSA_1.encrypt(USER_NAME, '')) == USER_NAME: with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + USER_NAME + ':' + 'download-share RSA_1 ' + file_path) info = 'invalid RSA_1' return False, info if not SHARE_RSA_2.decrypt(SHARE_PUBLIC_RSA_2.encrypt(USER_NAME, '')) == USER_NAME: with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + USER_NAME + ':' + 'download-share RSA_ ' + file_path) info = 'invalid RSA_2' return False, info # get AES key with open(EFS_DIR + 'user_encrypt_AES.json', 'r') as f: AES_data = json.load(f) cipheraes = AES_data[group_name] SHARE_AES = encrypt.decrypt_aes(SHARE_RSA_2, cipheraes) en_file_name = encrypt.encrypt_filename(SHARE_RSA_1, real_path) en_file_name = en_file_name.replace("/", r"_")[0:100] # download file os.system(PASS + 'scp ' + SERVER + en_file_name + ' ' + save_pos) os.rename(save_pos + '/' + en_file_name, save_pos + '/' + filename) with open(save_pos + '/' + filename, 'r') as f: cipherfile = f.read() signature = cipherfile[0:344] cipherfile = cipherfile[344:] with open(save_pos + '/' + filename, 'w') as f: f.write(cipherfile) verify = encrypt.verify_sign(SHARE_PUBLIC_RSA_3, signature, cipherfile) if not verify: info = 'the file has been modified illegally' os.remove(save_pos + '/' + filename) try: split_real_path = real_path.split('/') split_real_path = split_real_path[:-1] en_source = '/'.join(split_real_path) + '/' + en_file_name os.rename(real_path, en_source) os.system(PASS + 'scp ' + en_source + SERVER) os.rename(en_source, real_path) info = info + ' and the backup file has been uploaded, please download again' return False, info except: info = info + ' and fail to upload the backup file' return False, info else: try: # update backup with open(save_pos + '/' + filename, 'r') as f: cipherfile = f.read() with open(real_path, 'w') as f: f.write(cipherfile) plain = encrypt.decrypt_file(SHARE_AES, save_pos + '/' + filename) with open(save_pos + '/' + filename, 'w') as f: f.write(plain) info = 'succeed' return True, info except: info = 'decrypt error' return False, info info = 'succeed' return True, info
from encrypt import decrypt_file decrypt_file('key', '/wohooofileinput', 'here.json')