fork download
  1. // C++ code to implement Hill Cipher
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. // Following function generates the
  6. // key matrix for the key string
  7. void getKeyMatrix(string key, int keyMatrix[][3])
  8. {
  9. int k = 0;
  10. for (int i = 0; i < 3; i++)
  11. {
  12. for (int j = 0; j < 3; j++)
  13. {
  14. keyMatrix[i][j] = (key[k]) % 65;
  15. k++;
  16. }
  17. }
  18. }
  19.  
  20. // Following function encrypts the message
  21. void encrypt(int cipherMatrix[][1],
  22. int keyMatrix[][3],
  23. int messageVector[][1])
  24. {
  25. int x, i, j;
  26. for (i = 0; i < 3; i++)
  27. {
  28. for (j = 0; j < 1; j++)
  29. {
  30. cipherMatrix[i][j] = 0;
  31.  
  32. for (x = 0; x < 3; x++)
  33. {
  34. cipherMatrix[i][j] +=
  35. keyMatrix[i][x] * messageVector[x][j];
  36. }
  37.  
  38. cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
  39. }
  40. }
  41. }
  42.  
  43. // Function to implement Hill Cipher
  44. void HillCipher(string message, string key)
  45. {
  46. // Get key matrix from the key string
  47. int keyMatrix[3][3];
  48. getKeyMatrix(key, keyMatrix);
  49.  
  50. int messageVector[3][1];
  51.  
  52. // Generate vector for the message
  53. for (int i = 0; i < 3; i++)
  54. messageVector[i][0] = (message[i]) % 65;
  55.  
  56. int cipherMatrix[3][1];
  57.  
  58. // Following function generates
  59. // the encrypted vector
  60. encrypt(cipherMatrix, keyMatrix, messageVector);
  61.  
  62. string CipherText;
  63.  
  64. // Generate the encrypted text from
  65. // the encrypted vector
  66. for (int i = 0; i < 3; i++)
  67. CipherText += cipherMatrix[i][0] + 65;
  68.  
  69. // Finally print the ciphertext
  70. cout << " Ciphertext:" << CipherText;
  71. }
  72.  
  73. // Driver function for above code
  74. int main()
  75. {
  76. // Get the message to be encrypted
  77. string message = "ACT";
  78.  
  79. // Get the key
  80. string key = "GYBNQKURP";
  81.  
  82. HillCipher(message, key);
  83.  
  84. return 0;
  85. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
 Ciphertext:POH