如何对仅产生英语字母的python中的两个字符串进行XOR?

时间:2018-08-31 10:46:28

标签: python-2.7

我是python的初学者,并且以某种方式设法为One Time Pad Encryption创建代码。但是,我需要的结果只能是字母,而不是特殊的字符/符号。

import random
import string
plain=raw_input("Enter PlainText: ")
length=len(plain)
key = "".join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for i in range(length))
print "RANDOM KEY GENERATED: ",key

message=str(plain)
key1=str(key)
print "STRING 1",message
print "STRING 2",key1

arr1 = bytearray(message, 'utf-8')
print "ARRAY 1 : ",arr1

arr2 = bytearray(key, 'utf-8')
print "ARRAY 2 : ",arr2

b = bytearray(len(arr1))
for i in range(len(arr1)):
   b[i] = arr1[i] ^ arr2[i]

xored=list(b)
print "XORED LIST: ",xored

mystring=""
for char in xored:
   mystring=mystring+chr(char)
print "CIPHER TEXT IS: ",mystring

output of code

1 个答案:

答案 0 :(得分:0)

  

chr()参数chr()方法采用一个参数,即整数i

     

chr()返回: Unicode代码点为整数i的字符(字符串)

您只需要将mystring=mystring+chr(char)替换为mystring=mystring+str(char)

这是您的固定代码:

import random
import string

plain=raw_input("Enter PlainText: ")
length=len(plain)
key = "".join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for i in range(length))
print "RANDOM KEY GENERATED: ",key

message=str(plain)
key1=str(key)
print "STRING 1",message
print "STRING 2",key1

arr1 = bytearray(message, 'utf-8')
print "ARRAY 1 : ",arr1

arr2 = bytearray(key, 'utf-8')
print "ARRAY 2 : ",arr2

b = bytearray(len(arr1))
for i in range(len(arr1)):
   b[i] = arr1[i] ^ arr2[i]

xored=list(b)
print "XORED LIST: ",xored

mystring=""
for char in xored:
   mystring=mystring+str(char)
print "CIPHER TEXT IS: ",mystring

哪个输出:

Enter PlainText: Foo
RANDOM KEY GENERATED:  dAD
STRING 1 Foo
STRING 2 dAD
ARRAY 1 :  Foo
ARRAY 2 :  dAD
XORED LIST:  [34, 46, 43]
CIPHER TEXT IS:  344643