密码学 - 简单替换密码的加密



在上一章中,我们了解了简单替换密码究竟是什么,它是如何工作的,基本实现及其缺点。现在我们将学习使用 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++ 中实现简单替换密码加密,每种方法都有其自身的优势和实现细节。

广告
© . All rights reserved.