import os
import random


def generate_key(length):
    """生成给定长度的随机字节序列"""
    key = bytearray(length)
    for i in range(length):
        key[i] = random.randint(0, 255)
    return key


def xor_encrypt(plaintext, key):
    """对给定字符串进行异或加密"""
    ciphertext = bytearray(len(plaintext))
    for i in range(len(plaintext)):
        ciphertext[i] = plaintext[i] ^ key[i % len(key)]
    return ciphertext


def encrypt_file(filename, key):
    """对给定文件进行加密"""
    # 读取文件内容
    with open(filename, 'rb') as f:
        plaintext = f.read()

    # 对文件内容进行加密
    ciphertext = xor_encrypt(plaintext, key)

    # 将加密后的内容写回文件中
    with open(filename, 'wb') as f:
        f.write(ciphertext)


# 要加密的文件名和密钥长度
filename = 'test.txt'
key_length = 16

# 生成一个长度为16的随机密钥
key = generate_key(key_length)

# 对文件进行加密
encrypt_file(filename, key)

# 打印加密后的密文和密钥
with open(filename, 'rb') as f:
    ciphertext = f.read()
print("密文:", ciphertext.hex())
print("密钥:", key.hex())

标签: none

添加新评论