Python 密碼學 - XOR 過程



本章我們將瞭解 XOR 過程及其在 Python 中的編碼。

演算法

XOR 加密和解密演算法將明文轉換為 ASCII 位元組格式,並使用 XOR 過程將其轉換為指定的位元組。它為使用者提供了以下優點:

  • 快速計算
  • 左右兩側沒有區別
  • 易於理解和分析

程式碼

您可以使用以下程式碼段執行 XOR 過程:

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)

輸出

XOR 過程的程式碼將為您提供以下輸出:

xor

解釋

  • 函式xor_crypt_string()包含一個引數來指定編碼和解碼模式以及字串值。

  • 基本函式採用 base64 模組,該模組遵循 XOR 過程/運算來加密或解密明文/密文。

注意 - XOR 加密用於加密資料,並且難以透過暴力破解方法破解,即透過生成隨機加密金鑰來匹配正確的密文。

廣告