Python简单可逆加密代码

该代码示例展示了如何使用Python实现基于异或运算的简单加密和解密功能。通过将明文和密钥的ASCII码进行异或操作,然后将结果转化为16进制字符串,实现了加密过程。解密则是反向操作,从16进制字符串还原回ASCII码并再次异或。示例中还包含了一个DEMO,演示了加密和解密的过程。
摘要由CSDN通过智能技术生成

Python简单可逆加密代码

def encrypt(plaintext, key):
    """
    将明文使用给定的密钥进行加密
    :param plaintext: 明文
    :param key: 密钥
    :return: 密文
    """
    ciphertext = ""
    for i in range(len(plaintext)):
        # 获取字符的ASCII码并进行异或运算
        # chr(ord(plaintext[i]) ^ ord(key[i % len(key)])) 表示将密钥进行循环使用
        # 使用format()函数将异或运算的结果转化为16进制字符串,长度不足2位时前面补0
        ciphertext += format(ord(plaintext[i]) ^ ord(key[i % len(key)]), '02x')
    return ciphertext


def decrypt(ciphertext, key):
    """
    将密文使用给定的密钥进行解密
    :param ciphertext: 密文
    :param key: 密钥
    :return: 明文
    """
    plaintext = ""
    # 将16进制字符串按两位一组转换为ASCII码并进行异或运算
    for i in range(0, len(ciphertext), 2):
        plaintext += chr(int(ciphertext[i:i+2], 16) ^ ord(key[(i//2) % len(key)]))
    return plaintext

DEMO

key='12345678'
plaintext='12345'
ciphertext=encrypt(plaintext, key)
print(ciphertext)
plaintext=decrypt(ciphertext,key)
print(plaintext)
plaintext=decrypt(ciphertext,'abxcd')
print(plaintext)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

义薄云天us

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值