密碼學 - 仿射密碼



現在我們將學習仿射密碼及其加密和解密演算法。仿射密碼是單字母替換密碼的一個例子。它是一種加密策略。它也像一個秘密程式碼,將敏感內容轉換為編碼形式。

在仿射密碼中,訊息中的每個字母都透過遵循一個簡單的數學公式替換為另一個字母。在這個演算法中,我們將字母在字母集中的位置乘以一個數字,然後再加上另一個數字。此過程更改訊息,以便只有知道正確數字的人才能將其翻譯回其原始形式。

由於加密策略基本上是數學的,因此它與我們已經看到的其他情況略有不同。整個過程依賴於模m運算,其中m是字元集的長度。我們透過對明文字元應用方程來轉換明文。

仿射密碼加密

加密過程的第一步是將明文字母集中的每個字母轉換為其在 0 到 M-1 範圍內的對應數字。完成此操作後,每個字母的加密過程由下式給出:

E(x) = (Ax + B) mod M

其中,

  • E 是加密訊息。

  • x 是字母在字母集中的位置(例如,A=0,B=1,C=2,…,Z=25)

  • A 和 B 是密碼的金鑰。這表明我們在將明文字母的數值乘以 A 後,將 B 加到結果中。

  • M 表示模。

(也就是說,當我們將大數除以字母集的長度時,我們找到餘數部分。這確保了我們的新字母仍然在字母表內)。

仿射密碼解密

當我們必須使用仿射密碼加密系統解密密文時,我們將不得不執行與加密相反的過程。第一步是將每個密文字母轉換回其數值,就像我們在轉換訊息時所做的那樣。

然後,要解密每個數字,我們使用以下公式:

D(x)= C(x − B) mod M

其中,

  • D 代表解密訊息。

  • x 表示我們從密文字母獲得的數字。

  • B 表示我們在加密時新增以移動字母的數字。

  • C 是一個特殊的數字,稱為 A 的模乘法逆元。這是一個數字,當我們將其乘以 A 並不斷減去字母表的長度時,我們將得到 1。

  • M 是模或字母的長度。

讓我們看看下面的圖片,以簡單的方式理解加密和解密過程。

basic implementation of affine cipher

使用 Python 實現

現在,我們將使用不同的方法實現使用 Python 的仿射加密和解密程式:

  • 使用字典對映

  • 使用預定義金鑰

因此,我們將在以下部分中看到所有上述方法及其在 Python 中的實現:

使用字典對映

在這個例子中,我們將使用字典對映來使用 Python 建立仿射密碼演算法。字典對映的過程需要在解密或加密的情況下將每個字母轉換為其等效字母。

我們的加密和解密數學公式為仿射密碼中的這種對映提供了起點。字母表的原始字母用作字典的鍵,而其加密或解密版本用作值。可以使用程式碼中此字典訪問明文或密文中每個字母的加密或解密字母。

示例

以下是使用字典對映的仿射密碼加密和解密演算法的 Python 實現。請檢視下面的程式碼:

# Encryption function
def affine_encrypt(text, a, b):
   encrypted_text = ""
   for char in text:
      if char.isalpha():
         if char.isupper():
            encrypted_text += chr(((a * (ord(char) - ord('A')) + b) % 26) + ord('A'))
         else:
            encrypted_text += chr(((a * (ord(char) - ord('a')) + b) % 26) + ord('a'))
      else:
         encrypted_text += char
   return encrypted_text

# Decryption function
def affine_decrypt(text, a, b):
   decrypted_text = ""
   m = 26
   a_inv = pow(a, -1, m)
   for char in text:
      if char.isalpha():
         if char.isupper():
            decrypted_text += chr(((a_inv * (ord(char) - ord('A') - b)) % 26) + ord('A'))
         else:
            decrypted_text += chr(((a_inv * (ord(char) - ord('a') - b)) % 26) + ord('a'))
      else:
         decrypted_text += char
   return decrypted_text

# plain text message and keys
plain_text = "Nice to meet you!"
a = 5
b = 8

encrypted_text = affine_encrypt(plain_text, a, b)
print("Our Encrypted text:", encrypted_text)

decrypted_text = affine_decrypt(encrypted_text, a, b)
print("Our Decrypted text:", decrypted_text)

以下是上述示例的輸出:

輸入/輸出
Our Encrypted text: Vwsc za qccz yae!
Our Decrypted text: Nice to meet you!

使用預定義金鑰

此程式碼執行仿射密碼過程以編碼和解碼內容。它在 KEY 變數中使用預定義金鑰進行加密和解密。此變數是一個包含三個值的元組:(7, 3, 55)。這些值顯示仿射密碼的加密和解密金鑰。我們還將有另一個變數稱為 DIE,它表示字元集大小 (128)。

示例

以下是使用預定義金鑰的仿射密碼加密和解密演算法的 Python 實現。檢視下面的程式碼:

# Affine cipher Class
class affine_cipher(object):
   DIE = 128
   KEY = (7, 3, 55)

   def __init__(self):
     pass

   def encryptChar(self, char):
      K1, K2, kI = self.KEY
      return chr((K1 * ord(char) + K2) % self.DIE)

   def encrypt(self, string):
      return "".join(map(self.encryptChar, string))

   def decryptChar(self, char):
      K1, K2, KI = self.KEY
      return chr((KI * (ord(char) - K2)) % self.DIE)

   def decrypt(self, string):
      return "".join(map(self.decryptChar, string))

affine = affine_cipher()
print("Our Encrypted Text: ", affine.encrypt('Affine Cipher'))
print("Our Decrypted Text: ", affine.decrypt('JMMbFcXb[F!'))

以下是上述示例的輸出:

輸入/輸出
Our Encrypted Text:  JMMbFcXb[F!
Our Decrypted Text:  Affine Cipher

使用 Java 實現

本實現將使用Java程式語言來使用仿射密碼加密和解密訊息。因此,我們將在這裡使用兩個金鑰,第一個是乘法金鑰 (A),第二個是加法金鑰 (B)。這些金鑰將用於混合給定訊息中的字母,使其保密。對於解密訊息,將使用一種稱為模乘法逆的特殊數學公式來撤消加密。

示例

因此,下面給出了使用Java實現仿射密碼的方法:

public class AffineCipher {
    
   static final int A = 17; // Multiplicative Key
   static final int B = 20; // Additive Key

   // Function to find modular multiplicative inverse
   static int modInverse(int a, int m) {
      for (int x = 1; x < m; x++) {
         if (((a % m) * (x % m)) % m == 1) {
            return x;
         }
      }
      return -1; // If inverse is not there
   }
    
   // Function to encrypt plaintext
   static String encryptMessage(String pt) {
      StringBuilder ciphertext = new StringBuilder();
      for (int i = 0; i < pt.length(); i++) {
         char ch = pt.charAt(i);
         if (Character.isLetter(ch)) {
            if (Character.isUpperCase(ch)) {
               ciphertext.append((char) ('A' + (A * (ch - 'A') + B) % 26));
            } else {
               ciphertext.append((char) ('a' + (A * (ch - 'a') + B) % 26));
            }
         } else {
            ciphertext.append(ch);
         }
      }
      return ciphertext.toString();
   }
    
   // Function to decrypt ciphertext
   static String decryptMessage(String ciphertext) {
      StringBuilder pt = new StringBuilder();
      int aInverse = modInverse(A, 26);
      if (aInverse == -1) {
         return "Inverse doesn't exist";
      }
      for (int i = 0; i < ciphertext.length(); i++) {
         char ch = ciphertext.charAt(i);
         if (Character.isLetter(ch)) {
            if (Character.isUpperCase(ch)) {
               int x = (aInverse * (ch - 'A' - B + 26)) % 26;
               pt.append((char) ('A' + x));
            } else {
               int x = (aInverse * (ch - 'a' - B + 26)) % 26;
               pt.append((char) ('a' + x));
            }
         } else {
            pt.append(ch);
         }
      }
      return pt.toString();
   }
    
   public static void main(String[] args) {
      String pt = "Hello this is an example of affine cipher";

      String et = encryptMessage(pt); // Encrypted Text
      System.out.println("The Encrypted Text: " + et);

      String dt = decryptMessage(et); // Decrypted Text
      System.out.println("The Decrypted Text: " + dt);
   }
}

以下是上述示例的輸出:

輸入/輸出

The Encrypted Text: Jkzzy fjao ao uh kvuqpzk yb ubbahk capjkx
The Decrypted Text: Hello this is an example of affine cipher

使用C++的實現

我們將使用C++程式語言來實現仿射密碼,這是一種保持訊息秘密的方法。因此,這段程式碼的概念與我們在Java實現中使用的一樣,但區別在於我們將在這裡使用C++。

示例

因此,下面給出了C++中仿射密碼的實現:

#include <iostream>
#include <string>
using namespace std;

const int A = 17; // Multiplicative Key
const int B = 20; // Additive Key

// function to find mod inverse
int modInverse(int a, int m) {
   for (int x = 1; x < m; x++) {
      if (((a % m) * (x % m)) % m == 1) {
         return x;
      }
   }
   return -1; // If inverse is not there
}

// Function to encrypt plaintext
string encryptMessage(string plaintext) {
   string ciphertext = "";
   for (char ch : plaintext) {
      if (isalpha(ch)) {
         if (isupper(ch)) {
            ciphertext += (char)('A' + (A * (ch - 'A') + B) % 26);
         } else {
            ciphertext += (char)('a' + (A * (ch - 'a') + B) % 26);
         }
      } else {
         ciphertext += ch;
      }
   }
   return ciphertext;
}

// Function to decrypt ciphertext
string decryptMessage(string ciphertext) {
   string plaintext = "";
   int aInverse = modInverse(A, 26);
   if (aInverse == -1) {
      return "Inverse doesn't exist";
   }
   for (char ch : ciphertext) {
      if (isalpha(ch)) {
         if (isupper(ch)) {
            int x = (aInverse * (ch - 'A' - B + 26)) % 26;
            plaintext += (char)('A' + x);
         } else {
            int x = (aInverse * (ch - 'a' - B + 26)) % 26;
            plaintext += (char)('a' + x);
         }
      } else {
         plaintext += ch;
      }
   }
   return plaintext;
}

int main() {
   string pt = "Hello there i am working with Affine Cipher";
   string et = encryptMessage(pt);
   cout << "Encrypted Text: " << et << endl;

   string dt = decryptMessage(et);
   cout << "Decrypted Text: " << dt << endl;

   return 0;
}

以下是上述示例的輸出:

輸入/輸出

The Encrypted Text: Jkzzy fjkxk a uq eyxiahs eafj Ubbahk Capjkx
The Decrypted Text: Hello there i am working with Affine Cipher

特點

  • 易於理解和實現。

  • 字母表的大小可以調整。

  • 它允許使用不同的金鑰進行加密和解密。因此,它在選擇安全級別方面提供了靈活性。

  • 加密和解密過程包括數值運算,這為編碼的訊息增加了一層安全性。

缺點

  • 可能的金鑰數量受字母集大小的限制,這容易受到暴力攻擊。

  • 由於仿射密碼保留了字母頻率,因此它容易受到頻率分析攻擊。

  • 它只關注加密和解密,缺乏資料完整性驗證或傳送者身份驗證機制。

總結

在本章中,我們學習了仿射密碼演算法,用於加密和解密我們的秘密資訊。它使用數學公式來加密和解密給定的訊息。它有助於保護訊息安全,方法是將它們轉換成只有使用正確的數字才能理解的秘密程式碼。我們還看到了使用Python以不同方式實現仿射密碼的方法。一種方法涉及使用模算術運算,我們在其中將數字保持在特定範圍內。另一種方法使用字典對映,其中每個字母根據公式替換為其加密或解密版本。

廣告