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 compress_by_ext(extname, outname): global filecount1, filecount2 print("| * === %s ===" % outname) filecount1 = 0 filecount2 = 0 out_boot_path = out_path + '/boot.oxgame.' + outname out_game_path = out_path + '/game.bin.' + outname bootzip = zipfile.ZipFile(out_boot_path, 'w', zipfile.ZIP_DEFLATED) gamezip = zipfile.ZipFile(out_game_path, 'w', zipfile.ZIP_DEFLATED) traverse(dst_path, extname, bootzip, gamezip) gamezip.close() bootzip.close() encrypt.encrypt_file(out_boot_path) encrypt.encrypt_file(out_game_path) if len(preloadfiles) != filecount1: print("====================================== error ======================================") print("====================================== error ======================================") print("====================================== error ======================================") print("====================================== error ======================================") print("====================================== error ======================================") print("====================================== error ======================================") print("| * %s || count: %d" % (out_boot_path, filecount1)) print("| * %s || count: %d" % (out_game_path, filecount2))
def encrypt_file_use_existing_key(): try: # Select the main plain file to encrypt print( "\nStep 1: Please select your Main File (Plain Text) that you want to encrypt : " ) input("Press <ENTER> to continue...") try: main_file = filedialog.askopenfile( initialdir="/", title="Select Plain Text File To Encrypt") print("The selected main plain file is: " + main_file.name) # Select location to save the encrypted file print( "\nStep 2: Please give a name of encrypted file and select directory to save it : " ) input("Press <ENTER> to continue...") encrypt_file = filedialog.asksaveasfile( initialdir="/", title="Save Encrypted File", filetypes=(("encrypt files", "*.enc"), ("all files", "*.*"))) x = encrypt_file.name except AttributeError: print("Operation cancelled by the user!") else: # Trim data from the path value encrypt_file = x.split('/')[-1] + ".enc" os.remove( x) # Exception handle: remove file without .enc extension print("You have saved encrypted file as: " + encrypt_file) # Select a key file for encryption print("\nStep 3: Please select the Key File for encryption : ") input("Press <ENTER> to continue...") key_file = filedialog.askopenfile(initialdir="/", title="Select Key File") print("The key file you have selected to encrypt is: " + key_file.name) try: # Encryption process encrypt.encrypt_file(main_file.name, encrypt_file, key_file.name) # Update key & value with encrypted file names and their keys paired up if encrypt_key_value_dict.keys(): encrypt_key_value_dict[key_file.name].append(encrypt_file) else: encrypt_key_value_dict[key_file.name] = [encrypt_file] print("\nEncryption completed successfully and '" + encrypt_file + "' file is created.") input("Press <ENTER> to continue...") except AttributeError: print("Operation cancelled by the user!!") except FileNotFoundError: print("Exception: File Not Found!")
def filehash(filepath): encrypt_file(filepath) file = open(filepath + '.enc', 'rb') docfile = file.read() sha = hashlib.sha256() sha.update(docfile) sha256 = sha.hexdigest() os.remove(filepath + '.enc') return sha256
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 updatefile(path): URL_update = detailurl(path) log = [] # try: if os.path.isfile(observing_root + path): r = client.get(server_ip) if 'csrftoken' in client.cookies: csrftoken = client.cookies['csrftoken'] encrypt_file(observing_root + path) file = open(observing_root + path + '.enc', 'rb') docfile = file.read() sha = hashlib.sha256() sha.update(docfile) sha = sha.hexdigest() data = dict(path=path, owner='jatin', sha256=sha, docfile=docfile, isdir=False, schema=lcschema, csrfmiddlewaretoken=csrftoken) os.remove(observing_root + path + '.enc') r = client.put(URL_update, data=data, headers={ "Referer": server_ip, "X-CSRFToken": csrftoken }) if r.status_code != 200: dic = r.text[38:51] if dic == 'hash mismatch': log.append(' (failed (hash mismatch))'.ljust(30) + path) else: log.append(' (server error)'.ljust(30) + path) else: log.append(' (updated)'.ljust(30) + path) stamp = os.path.getmtime(observing_root + path) cur.execute( "INSERT INTO Files (filepath, sha256, stamp) VALUES (?,?,?)", [path, sha, str(stamp)]) else: stamp = os.path.getmtime(observing_root + path) cur.execute( "INSERT INTO Files (filepath, sha256, stamp) VALUES (?,?,?)", [path, None, str(stamp)]) log.append(' (file does not exist)'.ljust(30) + path) # except: # log.append(' (internal error)'.ljust(30)+path) return log
def uploadfile(path): URL_create = server_ip + 'api/file/' log = [] try: client.get(server_ip) if 'csrftoken' in client.cookies: csrftoken = client.cookies['csrftoken'] docfile = None sha256 = None isdir = True if os.path.isfile(observing_root + path): encrypt_file(observing_root + path) file = open(observing_root + path + '.enc', 'rb') docfile = file.read() sha = hashlib.sha256() sha.update(docfile) isdir = False sha256 = sha.hexdigest() os.remove(observing_root + path + '.enc') elif os.path.isdir(observing_root + path): pass else: # print(path,'(file does not exist)') log.append(' (file does not exist)'.ljust(30) + path) data = dict(path=path, sha256=sha256, docfile=docfile, isdir=isdir, schema=lcschema, csrfmiddlewaretoken=csrftoken, next='') r = client.post(URL_create, data=data, headers=dict(Referer=server_ip)) if r.status_code != 201: # print('(server error)') dic = r.text[38:51] if dic == 'hash mismatch': log.append(' (failed (hash mismatch))'.ljust(30) + path) else: log.append(' (server error)'.ljust(30) + path) else: # print(path, '(uploaded)') log.append(' (uploaded)'.ljust(30) + path) except: # print(path, '(failed)') log.append(' (internal error)'.ljust(30) + path) return log
def encrypt_app(): layout = [[sg.Text('Select the files to encrypt')], [sg.Input(), sg.FilesBrowse()], [sg.Submit(), sg.Cancel()]] window = sg.Window('Encrypt Files', layout) event, values = window.Read() window.Close() if (event == "Cancel"): app() x = values[0].split(";") a = len(x) for i in range(a): encrypt.encrypt_file(x[i])
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 encrypt_file(self): filename = fdialog.askopenfilename() key = self.create_key.get() self.t.destroy() result = encrypt.encrypt_file(filename, key) if result: self.log["text"]= "Encryption was Successful" else: self.log["text"]= "An error has occured"
def encrypt_file(self): filename = fdialog.askopenfilename() key = self.create_key.get() self.t.destroy() result = encrypt.encrypt_file(filename, key) if result: self.log["text"] = "Encryption was Successful" else: self.log["text"] = "An error has occured"
def upload_file(filename_ori): """ Encrypt and upload the file using random filename, also add record in list. """ # Encrypt the file data = None try: data = encrypt.encrypt_file(filename_ori) except: log.print_error("error", "failed to encrypt file '%s'" % (filename_ori)) return False # Store the filename, key, iv and tag to list filelist.append(data["filename_ori"], data["filename_rand"], data["key"], data["iv"], data["tag"]) # Upload cipher text to server return upload(data["filename_rand"])
Reads the content of the file and returns the password value. ''' file_content = file_read() for i in file_content: if i.isdigit(): return file_content.index(i)*file_content.index(i) def rm_tmp_img(): remove(temp_image) if argv[1] == 'setup': check_dir() imageCapture(temp_image) encode_base64(temp_image, face_lock_image) rm_tmp_img() if argv[1] == 'encrypt': check_dir() decode_base(temp_image, face_lock_image) if image_matching(temp_image) == True: encrypt_file(argv[2], pass_enc(file_read()[pass_value():pass_value()+100])) rm_tmp_img() if argv[1] == 'decrypt': check_dir() decode_base(temp_image, face_lock_image) if image_matching(temp_image) == True: decrypt_file(argv[2], pass_enc(file_read()[pass_value():pass_value()+100])) rm_tmp_img()
def upload_share(USER_NAME, args): file_path = args[0] group_name = args[1] loc_RSA_1 = args[2] loc_RSA_3 = args[3] if not os.path.isfile(file_path): info = 'no such file' return False, info if file_path[0] != '/': info = 'absolute file path only' return False, info with open(loc_RSA_1, 'r') as f: SHARE_RSA_1 = RSA.importKey(f.read()) with open(loc_RSA_3, 'r') as f: SHARE_RSA_3 = 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()) split_file_path = file_path.split('/') filename = split_file_path[-1] share_path = EFS_DIR + group_name + '/' + filename 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 + ':' + 'upload-share RSA_1 ' + file_path) info = 'invalid RSA_1' return False, info if not SHARE_RSA_3.decrypt(SHARE_PUBLIC_RSA_3.encrypt(USER_NAME, '')) == USER_NAME: with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + USER_NAME + ':' + 'upload-share RSA_3 ' + file_path) info = 'invalid RSA_3' return False, info with open(file_path, 'r') as f: data = f.read() with open(share_path, 'w') as f: f.write(data) # new AES key SHARE_AES = encrypt.generate_AES() EN_SHARE_AES = encrypt.encrypt_aes(SHARE_PUBLIC_RSA_2, SHARE_AES) with open(EFS_DIR + 'user_encrypt_AES.json', 'r') as f: AES_data = json.load(f) AES_data[group_name] = EN_SHARE_AES with open(EFS_DIR + 'user_encrypt_AES.json', 'w') as f: json.dump(AES_data, f) # encrypt filename en_share_path = encrypt.encrypt_filename(SHARE_RSA_1, share_path) en_share_path = en_share_path.replace("/", r"_")[0:100] # encrypt file content cipherfile = encrypt.encrypt_file(SHARE_AES, share_path) # sign the hash value of the file signature = encrypt.sign_file(SHARE_RSA_3, cipherfile) # len(signature) = 344 cipherfile = signature + cipherfile with open(EFS_DIR + group_name + '/' + en_share_path, 'w') as f: f.write(cipherfile) os.system(PASS + 'scp ' + EFS_DIR + group_name + '/' + en_share_path + ' ' + SERVER) os.rename(EFS_DIR + group_name + '/' + en_share_path, share_path) member = group_name.split('_') for i in member: user_path = EFS_DIR + i + '/' with open(user_path + 'share_mirror.json', 'r') as f: data = json.load(f) data['/' + i + '/share/' + USER_NAME + '/' + filename] = '/' + group_name + '/' + filename with open(user_path + 'share_mirror.json', 'w') as f: json.dump(data, f) info = 'succeed' return True, info
def upload(USER_NAME, USER_PATH, USER_PRK, args): # verify command SOURCE = args[0] dest = args[1] if dest[-1] == '/': dest = dest[:-1] if dest[0:2] == './': dest = dest[2:] if not os.path.isfile(SOURCE): info = 'no such source file' return False, info if dest[0] == '/': dest_path_split = dest.split('/') if USER_NAME != dest_path_split[1]: info = 'destination directory permission denied' with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + user + ':' + 'upload ' + dest) return False, info else: DEST = EFS_DIR + dest[1:] else: DEST = EFS_DIR + USER_PATH + '/' + dest if not os.path.isdir(DEST): info = 'no such destination directory' 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 file name source_split = SOURCE.split('/') filename = source_split[-1] DEST_FILE = DEST + '/' + filename en_file_name = encrypt.encrypt_filename(USER_PK, DEST_FILE) en_file_name = en_file_name.replace("/", r"_")[0:100] # encrypt file content cipherfile = encrypt.encrypt_file(USER_AES, SOURCE) # sign the hash value of the file signature = encrypt.sign_file(USER_PRK, cipherfile) # len(signature) = 344 cipherfile = signature + cipherfile # backup in the file system EN_DEST_FILE = DEST + '/' + en_file_name with open(EN_DEST_FILE, 'w') as f: f.write(cipherfile) # test: try to decrypt # plain = encrypt.decrypt_file(USER_AES, DEST_FILE) # with open(DEST_FILE, 'w') as f: # f.write(plain) # upload to the server os.system(PASS + 'scp ' + EN_DEST_FILE + SERVER) os.rename(EN_DEST_FILE, DEST_FILE) except: info = 'error in uploading' return False, info info = 'succeed' return True, info
def upload(USER_NAME, USER_PATH, USER_PRK, USER_IP, SOCKET, ALL_SOCKET, LOCK_SOCKET, args): # verify command SOURCE = args[0] dest = args[1] if dest[-1] == '/': dest = dest[:-1] if dest[0:2] == './': dest = dest[2:] if not os.path.isfile(SOURCE): info = 'no such source file' return False, info if dest[0] == '/': dest_path_split = dest.split('/') if USER_NAME != dest_path_split[1]: info = 'destination directory permission denied' with open(ILLIGAL_LOG_FILE, 'a') as f: f.write('\n' + user + ':' + 'upload ' + dest) return False, info else: DEST = EFS_DIR + dest[1:] else: DEST = EFS_DIR + USER_PATH + '/' + dest if not os.path.isdir(DEST): info = 'no such destination directory' 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 file name source_split = SOURCE.split('/') filename = source_split[-1] DEST_FILE = DEST + '/' + filename en_file_name = encrypt.encrypt_filename(USER_PK, DEST_FILE) en_file_name = en_file_name.replace("/", r"_")[0:100] # encrypt file content cipherfile = encrypt.encrypt_file(USER_AES, SOURCE) # sign the hash value of the file signature = encrypt.sign_file(USER_PRK, cipherfile) # len(signature) = 344 cipherfile = signature + cipherfile # backup in the file system EN_DEST_FILE = DEST + '/' + en_file_name with open(EN_DEST_FILE, 'w') as f: f.write(cipherfile) # test: try to decrypt # plain = encrypt.decrypt_file(USER_AES, DEST_FILE) # with open(DEST_FILE, 'w') as f: # f.write(plain) # inquire on namenode _inquire(en_file_name, SOCKET, len(cipherfile)) DataNode = _get_datanode(SOCKET) #_upload_DataNode(USER_IP, cipherfile[0:16384], DataNode_1, 1, en_file_name) # get lock 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) # upload to the datanode # os.system(PASS + 'scp ' + EN_DEST_FILE + SERVER) os.rename(EN_DEST_FILE, DEST_FILE) except: info = 'error in uploading' return False, info info = 'succeed' return True, info
########################################### # Now as user 1: # a.Create an encrypted file with a randomly generated secret key # i.Symmetric encryption, AES-128 file_to_encrypt = "encryptme.txt" encrypted_file = "encrypted.txt" encrypted_file_key = "encrypted.key" encrypted_file_iv = "encrypted.iv" signature_file = "encrypted.sig" #encrypts encryptme.txt to encrypted.txt using a random key original_random_key = os.urandom(16) encrypt_file(original_random_key, encrypted_file_key, encrypted_file_iv, file_to_encrypt, encrypted_file) # encrypts key_file key_file = "encrypted.key" encrypted_key_file = "encrypted_key.txt" backend = default_backend() with open(k1.user2_cert, 'rb') as file: certificate = x509.load_pem_x509_certificate(data=file.read(), backend=backend) user2_public_key = certificate.public_key() pad = asympadding.PKCS1v15() key_encrypted = user2_public_key.encrypt(original_random_key, padding=pad) with open(encrypted_key_file, 'wb') as file2: file2.write(key_encrypted)
def upload_file(request): user = request.user user_name = request.user.username academys = Academy.objects.all() form = UploadFileFormFromModel() if request.method == 'POST': if not time_out_valid(request.user): request.user.is_active = False request.user.save() logout(request) return HttpResponse("您的行为疑似机器登录上传,暂时将您封号,请联系本站管理员") try: info = DataOfUser.objects.get(user=request.user) except DataOfUser.DoesNotExist, ex: print ex return HttpResponse("请完善用户信息") form = UploadFileFormFromModel(request.POST, request.FILES) if form.is_valid(): if form.cleaned_data['share_type'] == '2': path = handle_uploaded_file(request.FILES['file'], request.user.username) path_of_model = make_file_path_for_model(request.user.username) + request.FILES['file'].name.split("/")[-1] key = create_key() encrypt_file(key, path, path_of_model) try: new_model_file = open(path_of_model, 'r') except IOError, ex: print ex if delete_file(path): new_file = FileFromUser() new_file.user = request.user new_file.share = form.cleaned_data['share'] new_file.share_type = form.cleaned_data['share_type'] new_file.key = key new_file.file = File(new_model_file) new_file.save() new_model_file.close() delete_file(path_of_model) else: raise Http404 print new_file.share print type(new_file.share) file_key_encrypt(request.user, new_file.id, new_file.share, new_file.key, 2) add_file_to_message_list(request.user, new_file) elif form.cleaned_data['share_type'] == '1': file_name = request.FILES['file'].name.split("/")[-1].lower() for item in danger_file_suffix: if file_name.endswith(item): return HttpResponse("文件名为可执行文件,可能威胁到服务器,请转为可共享文件分享") new_file = FileFromUser() new_file.user = request.user new_file.share = form.cleaned_data['share'] new_file.share_type = form.cleaned_data['share_type'] new_file.key = "public" new_file.file = request.FILES['file'] new_file.save() add_file_to_message_list(request.user, new_file) else: path = handle_uploaded_file(request.FILES['file'], request.user.username) path_of_model = make_file_path_for_model(request.user.username) + request.FILES['file'].name.split("/")[-1] key = create_key() encrypt_file(key, path, path_of_model) try: new_model_file = open(path_of_model, 'r') except IOError, ex: print ex if delete_file(path): new_file = FileFromUser() new_file.user = request.user new_file.share = form.cleaned_data['share'] new_file.share_type = form.cleaned_data['share_type'] new_file.key = key new_file.file = File(new_model_file) new_file.save() new_model_file.close() delete_file(path_of_model) else: raise Http404 print new_file.share print type(new_file.share) file_key_encrypt(request.user, new_file.id, new_file.share, new_file.key, 3)
def enc(): filename = input("Enter the name of the file you would like to encrypt: ") encrypt_file(filename, '0123456789123456')
def enc_file(self): print('encrypting file...') encrypt_file()