密碼學 - 簡單替換密碼的加密



在上一章中,我們瞭解了簡單替換密碼究竟是什麼,它是如何工作的,基本實現及其缺點。現在我們將學習使用 Python、Java 和 C++ 實現簡單替換密碼的不同方法。

Python 實現

因此,我們可以使用不同的方法來實現簡單替換密碼的加密,例如:

  • 使用指定的移位值

  • 使用字典對映

  • 直接使用 ASCII 值

因此,我們將在下面的章節中嘗試詳細介紹每種方法的概念,以便您可以更好地理解簡單替換密碼的加密。

方法 1:使用指定的移位值

在替換密碼中,明文中的每個字母都會被替換為字母表中固定數量位置後的字母。這種方法的主要概念是,我們將使用指定的移位值對明文進行加密。移位值是字母表中每個字母應移動的位置數。

以下是使用 Python 實現此方法:

示例

# encryption function
def substitution_encrypt(plain_text, shift):
   encrypted_text = ""
   for char in plain_text:
      # if the character is a letter
      if char.isalpha():
         # find the ASCII value of the character
         ascii_val = ord(char)
         # if the character is uppercase or lowercase
         if char.isupper():
            # shift the character within the range (65-90)
            shifted_ascii = ((ascii_val - 65 + shift) % 26) + 65
         else:
            # shift the character within the range (97-122)
            shifted_ascii = ((ascii_val - 97 + shift) % 26) + 97
         # change back to a character
         encrypted_char = chr(shifted_ascii)
         encrypted_text += encrypted_char
      else:
         encrypted_text += char
   return encrypted_text

#our plain text example
plaintext = "Hello, everyone!"
shift = 5
encrypted_text = substitution_encrypt(plaintext, shift)
print("Plaintext: ", plaintext)
print("Encrypted text:", encrypted_text)

以下是上述示例的輸出:

輸入/輸出
Plaintext:  Hello, everyone!
Encrypted text: Mjqqt, jajwdtsj!

方法 2:使用字典對映

現在我們將使用字典對映來實現簡單替換密碼的加密。因此,我們建立一個“對映”或“字典”,藉助它我們將字母表中的每個字母與另一個字母匹配。例如,'a' 可以對映到 'b','b' 可以對映到 'c',依此類推。然後,我們將使用此對映將明文中的每個字母替換為其相應的對映字母。如果對映中找不到字母(例如標點符號或數字),我們將保持不變。

以下是使用字典對映實現簡單替換密碼加密的 Python 程式碼。請參見下面的程式:

示例

# encryption function
def substitution_encrypt(plain_text, key):
   # a dictionary mapping for substitution
   mapping = {chr(97 + i): key[i] for i in range(26)}
   # Encrypt the plaintext
   encrypted_text = ''.join(mapping.get(char.lower(), char) for char in plain_text)
   return encrypted_text

# our plain text example
plaintext = "Hello, dear friend!"
key = "bcdefghijklmnopqrstuvwxyza"  # substitution key
encrypted_text = substitution_encrypt(plaintext, key)
print("Plaintext: ", plaintext)
print("Encrypted text:", encrypted_text)

以下是上述示例的輸出:

輸入/輸出
Plaintext:  Hello, dear friend!
Encrypted text: ifmmp, efbs gsjfoe!

方法 3:直接使用 ASCII 值

您可能知道,每個字元或字母在計算機中都有一個與其相關的唯一數字,稱為“ASCII 值”。在這種方法中,我們將直接操作這些 ASCII 值以移動明文中的每個字母。例如,'a' 的 ASCII 值可能為 97,因此如果我們將它移動 5 位,它將變為 102,即字母 'f'。

因此,以下是使用上述方法實現簡單替換密碼加密的 Python 程式碼:

示例

# encryption function
def substitution_encrypt(plain_text, shift):
   encrypted_text = ""
   for char in plain_text:
      if char.isalpha():
         # use ASCII values directly to shift characters
         ascii_val = ord(char)
         shifted_ascii = ascii_val + shift
         if char.isupper():
            if shifted_ascii > 90:
               shifted_ascii -= 26
            elif shifted_ascii < 65:
               shifted_ascii += 26
         elif char.islower():
            if shifted_ascii > 122:
               shifted_ascii -= 26
            elif shifted_ascii < 97:
               shifted_ascii += 26
         encrypted_text += chr(shifted_ascii)
      else:
         encrypted_text += char
   return encrypted_text

# function execution
plaintext = "Hello, my dear colleague!"
shift = 3
encrypted_text = substitution_encrypt(plaintext, shift)
print("PlainText: ", plaintext)
print("Encrypted text:", encrypted_text)

以下是上述示例的輸出:

輸入/輸出
PlainText:  Hello, my dear colleague!
Encrypted text: Khoor, pb ghdu froohdjxh!

Java 實現

在這個 Java 實現中,我們將建立一個簡單的替換密碼演算法。在這裡,我們使用一個概念,其中我們必須將明文中的每個字母替換為加密字母表中的相應字母。我們將藉助 HashMap 建立常規字母表和加密字母表之間的對映。然後,對於明文中的每個字母,我們將檢視其相應的加密字母,並將其新增到密文中。如果字元不在對映中(例如,標點符號或空格),我們將保持其在密文中不變。

示例

因此,使用 Java 實現簡單替換密碼如下:

import java.util.HashMap;
import java.util.Map;

public class SSC {

   private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
   private static final String encrypted_alphabet = "bcdefghijklmnopqrstuvwxyza";
   private static final Map<Character, Character> encryptionMap = new HashMap<>();

   static {
      for (int i = 0; i < alphabet.length(); i++) {
         encryptionMap.put(alphabet.charAt(i), encrypted_alphabet.charAt(i));
      }
   }

   public static String encrypt(String plaintext) {
      StringBuilder ciphertext = new StringBuilder();
      for (char c : plaintext.toLowerCase().toCharArray()) {
         if (encryptionMap.containsKey(c)) {
            ciphertext.append(encryptionMap.get(c));
         } else {
            ciphertext.append(c);
         }
      }
      return ciphertext.toString();
   }

   public static void main(String[] args) {
      String plaintext = "Hello Tutorialspoint";
      String encryptedText = encrypt(plaintext);
      System.out.println("Our Plaintext: " + plaintext);
      System.out.println("The Encrypted text: " + encryptedText);
   }
}

以下是上述示例的輸出:

輸入/輸出

Our Plaintext: Hello Tutorialspoint
The Encrypted text: ifmmp uvupsjbmtqpjou

C++ 實現

這是使用 C++ 實現簡單替換密碼的程式碼。因此,我們將使用與上述實現中相同的方法。

示例

使用 C++ 的實現如下:

#include <iostream>
#include <unordered_map>
#include <string>

using namespace std;

class SSC {
private:
   const string alphabet = "abcdefghijklmnopqrstuvwxyz";
   const string encrypted_alphabet = "bcdefghijklmnopqrstuvwxyza";
   unordered_map<char, char> encryptionMap;

public:
   SSC() {
      for (int i = 0; i < alphabet.length(); i++) {
         encryptionMap[alphabet[i]] = encrypted_alphabet[i];
      }
   }

   string encrypt(string plaintext) {
      string ciphertext = "";
      for (char c : plaintext) {
         if (encryptionMap.find(tolower(c)) != encryptionMap.end()) {
            ciphertext += encryptionMap[tolower(c)];
         } else {
            ciphertext += c;
         }
      }
      return ciphertext;
   }
};

int main() {
   SSC cipher;
   string plaintext = "hello there how are you!";
   string encryptedText = cipher.encrypt(plaintext);
   cout << "Our Plaintext: " << plaintext << endl;
   cout << "The Encrypted text: " << encryptedText << endl;
   return 0;
}

以下是上述示例的輸出:

輸入/輸出

Our Plaintext: hello there how are you!
The Encrypted text: ifmmp uifsf ipx bsf zpv!

總結

本章討論了實現簡單替換密碼加密的不同方法。這些方法提供了多種方法來在 Python、Java 和 C++ 中實現簡單替換密碼加密,每種方法都有其自身的優勢和實現細節。

廣告