# -*- coding:utf-8 -*-
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

# 生成一个长度为16的随机密钥
key = generate_key(16)
# print(key)
# print(key.hex())
# 要加密的字符串
plaintext = "比亚迪元EV360电池容量是42KWH(42度电),但充满需要5比亚迪元EV360电池容量是42KWH(42度电),但充满需要5比亚迪元EV360电池容量是42KWH(42度电),但充满需要5比亚迪元EV360电池容量是42KWH(42度电),但充满需要5比亚迪元EV360电池容量是42KWH(42度电),但充满需要5比亚迪元EV360电池容量是42KWH(42度电),但充满需要5比亚迪元EV360电池容量是42KWH(42度电),但充满需要5"

plaintext=str(plaintext)
# print(plaintext.encode())
# 对字符串进行异或加密
ciphertext = xor_encrypt(plaintext.encode(), key)

# 打印加密后的密文和密钥
print("密文:", ciphertext.hex())
print("密钥:", key.hex())

import binascii

def xor_decrypt(ciphertext, key):
    """对给定的密文进行异或解密"""
    plaintext = bytearray(len(ciphertext))
    for i in range(len(ciphertext)):
        plaintext[i] = ciphertext[i] ^ key[i % len(key)]
    return plaintext.decode()

# 用于解密的密钥和密文
# key = binascii.unhexlify('8f6a71e35bf0c6e7beec02d8c200f5c5')
# ciphertext = binascii.unhexlify('3845b075ae98b1c5f4d4d8c29e')
key=key

ciphertext=ciphertext

# 对密文进行异或解密
plaintext = xor_decrypt(ciphertext, key)

# 打印解密后的明文
print("明文:", plaintext)

标签: none

添加新评论