Cryptography With Python 简明教程
Cryptography with Python - XOR Process
在本章节中,让我们了解 XOR 过程及其在 Python 中的编码。
In this chapter, let us understand the XOR process along with its coding in Python.
Algorithm
加密和解密的 XOR 算法将明文转换为 ASCII 字节格式,并使用 XOR 过程将其转换为指定的字节。它为用户提供以下优势:-
XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR procedure to convert it to a specified byte. It offers the following advantages to its users −
-
Fast computation
-
No difference marked in left and right side
-
Easy to understand and analyze
Code
可以使用以下代码段执行 XOR 过程:-
You can use the following piece of code to perform XOR process −
def xor_crypt_string(data, key = 'awesomepassword', encode = False, decode = False):
from itertools import izip, cycle
import base64
if decode:
data = base64.decodestring(data)
xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
if encode:
return base64.encodestring(xored).strip()
return xored
secret_data = "XOR procedure"
print("The cipher text is")
print xor_crypt_string(secret_data, encode = True)
print("The plain text fetched")
print xor_crypt_string(xor_crypt_string(secret_data, encode = True), decode = True)
Explanation
-
The function xor_crypt_string() includes a parameter to specify mode of encode and decode and also the string value.
-
The basic functions are taken with base64 modules which follows the XOR procedure/ operation to encrypt or decrypt the plain text/ cipher text.
Note − XOR 加密用于加密数据,并且很难通过暴力攻击方法(这是一种通过生成随机加密密钥来匹配正确的密码文本)破解。
Note − XOR encryption is used to encrypt data and is hard to crack by brute-force method, that is by generating random encrypting keys to match with the correct cipher text.