1. 程式人生 > >python:異或加密演算法

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))