亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

安全有效地替換文件的最佳方法?

安全有效地替換文件的最佳方法?

躍然一笑 2023-07-05 15:49:21
我正在嘗試使用模塊就地加密文件cryptography,因此我不必緩沖文件的密文,這可能會占用大量內存,然后我將不得不用加密的文件替換原始文件。所以我的解決方案是加密一個塊明文,然后嘗試將其替換為一次 16 個字節的密文(AES-CTR 模式)。問題似乎是循環是無限循環。那么如何解決這個問題。你建議什么其他方法。使用下面這種方法有什么副作用。pointer = 0with open(path, "r+b") as file:   print("...ENCRYPTING")   while file:        file_data = file.read(16)        pointer += 16        ciphertext = aes_enc.update(file_data)        file.seek(pointer-16)        file.write(ciphertext)    print("...Complete...")
查看完整描述

2 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

  • 那么如何解決這個問題。

正如 Cyril Jouve 已經提到的,檢查是否有 file_data

  • 你建議什么其他方法。

  • 使用下面這種方法有什么副作用。

以 16 字節為單位的塊讀取相對較慢。我猜你有足夠的內存來讀取更大的塊,如 4096、8192 ...

除非您有非常大的文件和有限的磁盤空間,否則我認為在同一個文件中讀取和寫入沒有任何好處。如果發生錯誤并且操作系統已經將數據寫入磁盤,您將丟失原始數據,并且將得到一個不完整的加密文件,您不知道其中哪一部分被加密。

創建新的加密文件然后刪除并重命名(如果沒有錯誤)會更容易且更省錢。

加密到新文件,捕獲異常,檢查加密文件的存在和大小,僅在一切正常的情況下刪除源并重命名加密文件。

import os


path = r'D:\test.dat'


input_path = path

encrypt_path = path + '_encrypt'


try:

    with open(input_path, "rb") as input_file:

        with open(encrypt_path, "wb") as encrypt_file:


            print("...ENCRYPTING")


            while True:


                file_data = input_file.read(4096)

                if not file_data:

                    break


                ciphertext = aes_enc.update(file_data)

                encrypt_file.write(ciphertext)


            print("...Complete...")


    if os.path.exists(encrypt_path):

        if os.path.getsize(input_path) == os.path.getsize(encrypt_path):

            print(f'Deleting {input_path}')

            os.remove(input_path)

            print(f'Renaming {encrypt_path} to {input_path}')

            os.rename(encrypt_path, input_path)


except Exception as e:

    print(f'EXCEPTION: {str(e)}')


查看完整回答
反對 回復 2023-07-05
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

文件對象沒有“真實性”,因此您不能將其用作循環的條件。

當 read() 返回空字節對象時,文件位于 EOF ( https://docs.python.org/3/library/io.html#io.BufferedIOBase.read )

with open(path, "r+b") as file:

   print("...ENCRYPTING")

    while True:

        file_data = file.read(16)

        if not file_data:

            break

        ciphertext = aes_enc.update(file_data)

        file.seek(-len(file_data), os.SEEK_CUR)

        file.write(ciphertext)

    print("...Complete...")


查看完整回答
反對 回復 2023-07-05
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號