密碼學 - 異或加密



異或函式廣泛應用於密碼學、數字邏輯電路、網路保護以及 Python、Java 和 C++ 等程式語言。異或運算也稱為“互斥或”。

邏輯函式異或(互斥或)比較兩個二進位制數字,如果它們不同則返回 1。如果兩個位完全相等,則異或函式返回 0。換句話說,如果其中一個二進位制數字為 1 但不是兩個都為 1,則異或給出 1。

正如我們上面討論的,異或可以用於密碼學中的加密。因此,藉助異或加密,我們可以加密難以使用蠻力破解的資料。例如,建立與正確金鑰匹配的隨機加密金鑰。

使用 Python 實現

我們可以使用以下 Python 方法實現異或加密:

  • 使用 For 迴圈和固定金鑰

  • 使用隨機金鑰生成

  • 使用 base64 模組

在接下來的部分中,我們將嘗試簡要解釋這些方法中的每一種,以便您能夠更好地理解使用 Python 的異或加密。

方法 1:使用 for 迴圈和固定金鑰

異或加密是一種簡單的對稱加密演算法,其中輸入訊息中的每個單獨字元都使用異或運算與金鑰組合。因此,我們可以使用異或運算逐個字元地加密我們的輸入訊息,並且在這裡我們可以為每個字元使用一個固定金鑰。在我們的例子中,金鑰是“T”。然後將異或運算的結果轉換回字元。

使用金鑰對每個字元進行異或運算的過程隱藏了原始訊息,使其在沒有加密金鑰的情況下難以閱讀。

以下是在明文中執行異或加密的示例:

示例

#Our XOR encryption function
def xorEncrypt(inpString): 
   my_xor_key = 'T'
   length = len(inpString)
   encrypted_msg = ""
   for i in range(length): 
      encrypted_msg += chr(ord(inpString[i]) ^ ord(my_xor_key))

   return encrypted_msg

demoMsg = "This is Tutorialspoint"

# Encrypt the string 
print("Original Message: ", demoMsg)
encrypted_message = xorEncrypt(demoMsg)
print("Our Encrypted Message: ", encrypted_message) 

以下是上述示例的輸出:

輸入/輸出
Original Message:  This is Tutorialspoint
Our Encrypted Message:  <='t='t! ;&=58'$;=: 

方法 2:使用隨機金鑰生成

在這種方法中,我們將使用 Python 的 random 模組生成隨機金鑰,以建立與訊息長度相同的金鑰用於異或加密。它使用 random.choice() 方法從 string 模組中隨機選擇 ASCII 字元。

在 xorEncrypt 函式中,生成的金鑰和訊息作為引數傳遞。zip 函式用於同時迭代訊息和金鑰的對應字元。

此過程為加密過程增加了隨機性和安全性。

以下是使用隨機金鑰生成進行異或加密的 Python 實現:

示例

import random
import string

#Generate random key
def generate_key(length):
   return ''.join(random.choice(string.printable) for _ in range(length))

# XOR Encryption function
def xorEncrypt(message, key):
   encrypted = ''.join(chr(ord(char) ^ ord(key_char)) for char, key_char in zip(message, key))
   return encrypted

#Function execution and input message
message = "Hello, Everyone!"
key = generate_key(len(message))
encrypted_msg = xorEncrypt(message, key)
print("Encrypted Message:", encrypted_msg)
decrypted_msg = xorEncrypt(encrypted_msg, key)
print("Decrypted Message:", decrypted_msg)

以下是上述示例的輸出:

輸入/輸出
Encrypted Message: e-2( vH#R\29 
Decrypted Message: Hello, Everyone!

方法 3:使用 base64 模組

Python 中的 base64 模組提供使用 Base64 編碼對資訊進行編碼和解碼的功能。因此,我們將使用使用者定義的金鑰對輸入訊息執行異或加密。加密訊息後,我們將使用 base64 對其進行編碼以建立加密訊息。

這是一個實現,它顯示了使用使用者定義的金鑰進行異或加密,然後使用 base64 對加密的訊息進行編碼:

示例

import base64

def xorEncrypt(message, key):
   encrypted = ''.join(chr(ord(char) ^ ord(key[i % len(key)])) for i, char in enumerate(message))
   return encrypted

def main():
   try:
      message = "Hello my name is Azaad"
      key = "T"
      print("Our Original Message is:", message)
      # Encrypt the message using XOR encryption
      encrypted_message = xorEncrypt(message, key)

      # Encode the encrypted message using base64
      encoded_message = base64.b64encode(encrypted_message.encode()).decode()

      print("Encrypted and encoded message:", encoded_message)

   except Exception as e:
      print("An error occurred:", str(e))

if __name__ == "__main__":
   main()

以下是上述示例的輸出:

輸入/輸出
Our Original Message is: Hello my name is Azaad
Encrypted and encoded message: HDE4ODt0OS10OjU5MXQ9J3QVLjU1MA==

使用 Java 實現

在此實現中,我們將使用 Java 的 Base64 類來實現 Base64 編碼和解碼功能。此類僅包含用於獲取 Base64 編碼方法的編碼器和解碼器的靜態方法。此類的實現支援 RFC 4648 和 RFC 2045 中指定的 Base64 型別。

示例

因此,以下是使用 Java 的 Base64 類實現 Base64 編碼和解碼的方法

import java.util.Base64;

public class Base64Class {
   public static void main(String[] args) {
      // Encoding process
      String plaintext = "Hello, Tutorialspoint!";
      String encoded_message = Base64.getEncoder().encodeToString(plaintext.getBytes());
      System.out.println("The Encoded string: " + encoded_message);

      // Decoding process
      byte[] decodedBytes = Base64.getDecoder().decode(encoded_message);
      String decodedString = new String(decodedBytes);
      System.out.println("The Decoded string: " + decodedString);
   }
}

以下是上述示例的輸出:

輸入/輸出

The Encoded string: SGVsbG8sIFR1dG9yaWFsc3BvaW50IQ==
The Decoded string: Hello, Tutorialspoint!

使用 C++ 實現

C++ 程式碼實現了一個將字串編碼為 Base64 的函式。在這裡,我們將主要使用 vector 和 iomanip 庫來實現 Base64。Vector 庫包含有用資料結構和函式的定義和實現,而 iomanip 是一個庫,主要用於操縱 C++ 程式的輸出。

此程式碼基本上將每個字元轉換為其相應的 Base64 成本並將其追加到輸出字串中。類似地,解密功能將每個 Base64 字元轉換回其唯一值並將其追加到輸出字串中。這樣,原始字串就會被重建。

示例

以下是使用 C++ 的實現

#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>

std::string base64_encode(const std::string &in) {
   std::string out;

   std::string base64_chars =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      "abcdefghijklmnopqrstuvwxyz"
      "0123456789+/";

   int val = 0, valb = -6;
   for (unsigned char c : in) {
      val = (val << 8) + c;
      valb += 8;
      while (valb >= 0) {
         out.push_back(base64_chars[(val >> valb) & 0x3F]);
         valb -= 6;
      }
   }
   if (valb > -6)
      out.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
   while (out.size() % 4)
      out.push_back('=');
   return out;
}

std::string base64_decode(const std::string &in) {
   std::string out;

   std::string base64_chars =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      "abcdefghijklmnopqrstuvwxyz"
      "0123456789+/";

   std::vector<int> base64_reverse_chars(256, -1);
   for (int i = 0; i < 64; i++) {
      base64_reverse_chars[base64_chars[i]] = i;
   }

   int val = 0, valb = -8;
   for (unsigned char c : in) {
      if (base64_reverse_chars[c] == -1)
         break;
      val = (val << 6) + base64_reverse_chars[c];
      valb += 6;
      if (valb >= 0) {
         out.push_back(char((val >> valb) & 0xFF));
         valb -= 8;
      }
   }
   return out;
}

int main() {
   std::string plaintext = "Hello, Everyone. This world is beautiful!";
   std::string es = base64_encode(plaintext);
   std::cout << "The Encoded string: " << es << std::endl;

   std::string ds = base64_decode(es);
   std::cout << "The Decoded string: " << ds << std::endl;

   return 0;
}

以下是上述示例的輸出:

輸入/輸出

The Encoded string: SGVsbG8sIEV2ZXJ5b25lLiBUaGlzIHdvcmxkIGlzIGJlYXV0aWZ1bCE=
The Decoded string: Hello, Everyone. This world is beautiful!

優勢

使用異或加密過程加密訊息有一些優勢 -

  • 異或加密非常簡單易於實現和理解。

  • 此方法計算效率高,使其成為一種快速的加密方法。

  • 異或加密是一種對稱加密,因此與非對稱加密方法相比,它簡化了金鑰管理。

  • 它可以透過使用不同的金鑰輕鬆自定義,從而允許各種加密變化。

缺點

以下是需要注意的一些異或加密的缺點 -

  • 異或加密需要一個安全的金鑰交換過程來確保金鑰的機密性。

  • 它容易受到已知明文攻擊,攻擊者可以在其中猜測明文和密文中模式以獲取金鑰或解密其他訊息。

  • 在這種技術中,我們對多個訊息重複使用相同的金鑰。這會削弱異或加密的安全性。

  • 它不適合加密大量資料,因為它缺乏像 AES 這樣的現代加密演算法提供的安全功能。

廣告