pythonファイルの暗号化と復号化の方法は何ですか

Pythonファイル暗号化と復号化の方法は次のようにいくつかあります:

  1. 暗号技術
from cryptography.fernet import Fernet

# 生成密钥
key = Fernet.generate_key()

# 创建加密器
cipher = Fernet(key)

# 加密文件
with open('plain.txt', 'rb') as file:
    plaintext = file.read()
encrypted_text = cipher.encrypt(plaintext)

# 将加密文件写入新文件
with open('encrypted.txt', 'wb') as file:
    file.write(encrypted_text)

# 解密文件
with open('encrypted.txt', 'rb') as file:
    encrypted_text = file.read()
decrypted_text = cipher.decrypt(encrypted_text)

# 将解密文件写入新文件
with open('decrypted.txt', 'wb') as file:
    file.write(decrypted_text)
  1. 暗号化
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.backends import default_backend

# 生成RSA密钥对
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()

# 保存私钥到文件
with open('private_key.pem', 'wb') as file:
    file.write(
        private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )
    )

# 保存公钥到文件
with open('public_key.pem', 'wb') as file:
    file.write(
        public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
    )

# 加密文件
with open('plain.txt', 'rb') as file:
    plaintext = file.read()
encrypted_text = public_key.encrypt(
    plaintext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 将加密文件写入新文件
with open('encrypted.txt', 'wb') as file:
    file.write(encrypted_text)

# 解密文件
with open('encrypted.txt', 'rb') as file:
    encrypted_text = file.read()
decrypted_text = private_key.decrypt(
    encrypted_text,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 将解密文件写入新文件
with open('decrypted.txt', 'wb') as file:
    file.write(decrypted_text)
  1. zipファイル
import zipfile
import shutil
from cryptography.fernet import Fernet

# 压缩文件
shutil.make_archive('archive', 'zip', '.', 'plain.txt')

# 加密压缩文件
with open('archive.zip', 'rb') as file:
    plaintext = file.read()
    
# 使用对称加密
key = Fernet.generate_key()
cipher = Fernet(key)
encrypted_text = cipher.encrypt(plaintext)

# 将加密文件写入新文件
with open('encrypted.zip', 'wb') as file:
    file.write(encrypted_text)

# 解密文件
with open('encrypted.zip', 'rb') as file:
    encrypted_text = file.read()

# 使用对称解密
decrypted_text = cipher.decrypt(encrypted_text)

# 将解密文件写入新文件
with open('decrypted.zip', 'wb') as file:
    file.write(decrypted_text)

# 解压缩文件
with zipfile.ZipFile('decrypted.zip', 'r') as zip_ref:
    zip_ref.extractall('.')

暗号化および復号化を行う際は、鍵の安全を確保してください。

bannerAds