image.png

    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. string encrypt(string pt, string key)
    4. {
    5. string ct = ""; // 密文
    6. int k = 0; //控制key的长度
    7. //ceil(a) 返回大于a的最小整数
    8. int row = ceil((float)pt.length() / key.length()); // 行数
    9. int col = key.length(); //列数
    10. std::vector<std::vector<int> > Matx(row, vector<int>(col, 0)); ///初始化row * col二维动态数组Matx,初始化值为0
    11. cout << "\n加密矩阵为 :" << endl;
    12. for (int i = 0; i < row; i++)
    13. {
    14. for (int j = 0; j < col; j++)
    15. {
    16. if (k < pt.length())
    17. {
    18. cout <<(char) (Matx[i][j] = pt[k++]) << " ";
    19. }
    20. else
    21. {
    22. cout << (char)(Matx[i][j] = 'x') << " ";
    23. }
    24. }
    25. cout << endl;
    26. }
    27. for (int i = 0; i < col; i++)
    28. {
    29. for (int j = 0; j < row; j++)
    30. {
    31. ct += Matx[j][key.find(i + '1')]; //密文抄送
    32. }
    33. }
    34. return ct;
    35. }
    36. string decrypt(string ct, string key)
    37. {
    38. string pt = ""; // plaintext
    39. int k = 0; // ciptext iterator
    40. int num_row = ceil((float)ct.length() / key.length());
    41. int num_col = key.length();
    42. std::vector<std::vector<int> > Matx(num_row, vector<int>(num_col, 0));
    43. for (int i = 0; i < num_col; i++)
    44. {
    45. for (int j = 0; j < num_row; j++)
    46. {
    47. Matx[j][key.find(i + '1')] = ct[k++];
    48. }
    49. }
    50. for (int i = 0; i < num_row; i++)
    51. {
    52. for (int j = 0; j < num_col; j++)
    53. {
    54. pt += Matx[i][j];
    55. }
    56. }
    57. return pt;
    58. }
    59. int main()
    60. {
    61. string plaintext, key, ciphertext, decryptext;
    62. /*cout << "Enter text : ";
    63. cin >> plaintext;*/
    64. plaintext = "transpoipher";
    65. /*cout << "Enter key : ";
    66. cin >> key;*/
    67. key = "4231";
    68. cout << "\n明文 \t:" << plaintext << endl;
    69. ciphertext = encrypt(plaintext, key);
    70. cout << "\n密文 \t: " << ciphertext << endl;
    71. decryptext = decrypt(ciphertext, key);
    72. cout << "\n解密 \t: " << decryptext << endl;
    73. }