密碼學 - 檔案解密



檔案解密是一種解密方法,它將檔案轉換回明文或可讀資料。使用此方法可確保授權人員可以訪問您的資料,他們可以使用解密金鑰讀取內容。

在本章中,我們將看到不同的解密技術來解密檔案資料。讓我們深入探討。

檔案解密的基本方法

解密是將加密資料更改回其原始可讀形式的過程。以下是檔案解密的一些基本方法:

對稱金鑰解密

單個金鑰用於加密和解密。要解密檔案,請使用與加密檔案時相同的金鑰。解密過程通常涉及使用解密金鑰將加密演算法的逆運算新增到加密資料中。

from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Read the file
with open('plain_text.txt', 'rb') as f:
   plaintext = f.read()

# Encrypt the file
encrypted_text = cipher_suite.encrypt(plaintext)

# Write the encrypted file
with open('encrypted_file.txt', 'wb') as f:
   f.write(encrypted_text)
    
# Print message after file is encrypted
print("File encrypted successfully.")


# Decrypt the file
decrypted_text = cipher_suite.decrypt(encrypted_text)

# Write the decrypted file
with open('decrypted_file.txt', 'wb') as f:
   f.write(decrypted_text)
    
# Print message after file is decrypted
print("File decrypted successfully.")

輸出

File encrypted successfully.
File decrypted successfully.

請參見下面的輸出影像,其中顯示了plain_text.txt、encrypted_file.txt和decrypted_file.txt檔案。

Python File Decryption

非對稱金鑰解密

非對稱金鑰加密需要兩個金鑰:公鑰和私鑰。公鑰用於加密,私鑰用於解密。要解密非對稱加密的檔案,您需要私鑰。非對稱加密通常用於安全通訊和金鑰交換。

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

# Generate key pair
private_key = rsa.generate_private_key(
   public_exponent=65537,
   key_size=2048
)
public_key = private_key.public_key()

# Save private key
with open("private.pem", "wb") as f:
   f.write(
      private_key.private_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PrivateFormat.TraditionalOpenSSL,
         encryption_algorithm=serialization.NoEncryption()
      )
   )

# Save public key
with open("public.pem", "wb") as f:
   f.write(
      public_key.public_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PublicFormat.SubjectPublicKeyInfo
      )
   )

def encrypt_file(file_path, public_key_path, output_path):
   # Load public key
   with open(public_key_path, "rb") as f:
      public_key = serialization.load_pem_public_key(f.read())

   # Encrypt file
   with open(file_path, "rb") as f:
      plaintext = f.read()
   ciphertext = public_key.encrypt(
      plaintext,
      padding.OAEP(
         mgf=padding.MGF1(algorithm=hashes.SHA256()),
         algorithm=hashes.SHA256(),
         label=None
      )
   )

   # Save encrypted file
   with open(output_path, "wb") as f:
      f.write(ciphertext)

def decrypt_file(file_path, private_key_path, output_path):
   # Load private key
   with open(private_key_path, "rb") as f:
      private_key = serialization.load_pem_private_key(
         f.read(),
         password=None
      )

   # Decrypt file
   with open(file_path, "rb") as f:
      ciphertext = f.read()
   plaintext = private_key.decrypt(
      ciphertext,
      padding.OAEP(
         mgf=padding.MGF1(algorithm=hashes.SHA256()),
         algorithm=hashes.SHA256(),
         label=None
      )
   )

   # Save decrypted file
   with open(output_path, "wb") as f:
      f.write(plaintext)

# Encrypt file
encrypt_file("plain_text.txt", "public.pem", "encrypted_file.bin")

# Decrypt file
decrypt_file("encrypted_file.bin", "private.pem", "decrypted_plaintext.txt")

輸出

使用“python program.py”執行上述程式碼後,它將建立公鑰和私鑰,然後使用公鑰加密名為plain_text.txt的檔案,然後使用私鑰解密加密的檔案。

Asymmetric File Decryption

基於密碼的解密

密碼或密碼短語會建立一個用於加密和解密的金鑰。相同的密碼用於加密和解密資料。要解密受基於密碼的加密保護的檔案,您必須輸入正確的密碼。

from cryptography.fernet import Fernet

# get password from user
password = input("Enter password: ").encode()

# derive key from password
key = Fernet.generate_key()

# create Fernet cipher suite with the derived key
cipher_suite = Fernet(key)

# read the encrypted file
with open('encrypted_file.txt', 'rb') as f:
   encrypted_text = f.read()

# decrypt the file
try:
   decrypted_text = cipher_suite.decrypt(encrypted_text)
   # write the decrypted file
   with open('decrypted_file.txt', 'wb') as f:
      f.write(decrypted_text)
   print("File decrypted successfully.")
except Exception as e:
   print("Error decrypting file:", str(e))

輸入/輸出

Enter password: 12345
Error decrypting file:    

金鑰派生

某些加密方法使用金鑰派生函式 (KDF) 從密碼或密碼短語生成金鑰。然後使用生成的金鑰進行加密和解密。金鑰派生確保使用相同的密碼建立相同的金鑰,從而允許安全解密。

初始化向量 (IV) 的使用

初始化向量 (IV) 用於加密演算法中,以防止密文與明文相同。解密檔案時,通常需要同時提供 IV 和解密金鑰。IV 通常包含在加密檔案中或與其一起傳送。

廣告