實現仿射密碼的 C++ 程式


在仿射密碼中,字母中的每個字母都對映到其數字等價物,這是一種單字母替換密碼。使用簡單的數學函式進行加密並轉換回字母。

在仿射密碼中,首先將大小為 m 的字母對映到 0 ... m-1 範圍內的整數,

仿射密碼的“金鑰”由 2 個數字 a 和 b 組成。應選擇 a 與 m 互為素數。

加密

若要轉換整數,它使用模運算,其中每個明文對應於另一個對應於密文的一個整數。單個字母的加密函式為

E ( x ) = ( a x + b ) mod m
modulus m: size of the alphabet
a and b: key of the cipher.

解密

在解密中,將每個密文轉換為其整數值。解密函式為

D ( x ) = a^-1 ( x - b ) mod m
a^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation
1 = a^-1 mod m.

以下是一個 C++ 程式來實現此過程。

演算法

Begin
Function encryption(string m)
   for i = 0 to m.length()-1
      if(m[i]!=' ')
         c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A')
      else
         c += m[i]
   return c
End
Begin
Function decryption(string c)
   Initialize a_inverse = 0
   Initialize flag = 0
   For i = 0 to 25
      flag = (a * i) % 26
      if (flag == 1)
         a_inverse = i
      done
   done
   For i = 0 to c.length() - 1
      if(c[i]!=' ')
         m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A')
      else
         m = m+ c[i]
   done
End

示例

#include<bits/stdc++.h>
using namespace std;
static int a = 7;
static int b = 6;
string encryption(string m) {
   //Cipher Text initially empty
   string c = "";
   for (int i = 0; i < m.length(); i++) {
      // Avoid space to be encrypted
      if(m[i]!=' ')
         // added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
         c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A');
      else
         //else append space character
         c += m[i];
   }
   return c;
}
string decryption(string c) {
   string m = "";
   int a_inverse = 0;
   int flag = 0;
   //Find a^-1 (the multiplicative inverse of a
   //in the group of integers modulo m.)
   for (int i = 0; i < 26; i++) {
      flag = (a * i) % 26;
      //Check if (a * i) % 26 == 1,
      //then i will be the multiplicative inverse of a
      if (flag == 1) {
         a_inverse = i;
      }
   }
   for (int i = 0; i < c.length(); i++) {
      if(c[i] != ' ')
         // added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
         m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A');
      else
         //else append space character
         m += c[i];
   }
   return m;
}
int main(void) {
   string msg = "TUTORIALSPOINT";
   string c = encryption(msg);
   cout << "Encrypted Message is : " << c<<endl;
   cout << "Decrypted Message is: " << decryption(c);
   return 0;
}

輸出

Encrypted Message is : JQJAVKGFCHAKTJ
Decrypted Message is: TUTORIALSPOINT

更新時間: 2019 年 7 月 30 日

3K+ 觀看次數

提升您的 事業

填寫課程並獲取認證

開始
廣告