python:异或加密算法

  • Post author:
  • Post category:python


def encode(plaintext,key):
    key = key * (len(plaintext) // len(key)) + key[:len(plaintext) % len(key)]#取整数/余数
    ciphertext=[]
    for i in range(len(plaintext)):
        ciphertext.append(str(ord(plaintext[i])^ord(key[i])))
    return ','.join(ciphertext)
#解密
def decode(ciphertext,key):
    ciphertext=ciphertext.split(',')
    key=key*(len(ciphertext)//len(key))+key[:len(ciphertext)%len(key)]#取整数/余数
    plaintext=[]
    for i in range(len(ciphertext)):
        plaintext.append(chr(int(ciphertext[i])^ord(key[i])))
    return ''.join(plaintext)

if __name__ == '__main__':
    functions=input('输入A加密,输入B解密,其它关闭>>>>')
    if functions=='A':
        plaintext=input('请输入加密文字明文>>>')
        key=input('请输入加密密钥>>>')
        print('密文',encode(plaintext,key))
    if functions=='B':
        ciphertext = input('请输入解密文字明文>>>')
        key = input('请输入解密密钥>>>')
        print('明文',decode(ciphertext,key))



版权声明:本文为weixin_42557907原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。