fork download
  1.  
  2. import math
  3.  
  4. key = "HACK"
  5.  
  6. def encryptMessage(msg):
  7. cipher = ""
  8.  
  9.  
  10. k_indx = 0
  11.  
  12. msg_len = float(len(msg))
  13. msg_lst = list(msg)
  14. key_lst = sorted(list(key))
  15.  
  16.  
  17. col = len(key)
  18.  
  19.  
  20. row = int(math.ceil(msg_len / col))
  21.  
  22. fill_null = int((row * col) - msg_len)
  23. msg_lst.extend('_' * fill_null)
  24.  
  25.  
  26. matrix = [msg_lst[i: i + col]
  27. for i in range(0, len(msg_lst), col)]
  28.  
  29.  
  30. for _ in range(col):
  31. curr_idx = key.index(key_lst[k_indx])
  32. cipher += ''.join([row[curr_idx]
  33. for row in matrix])
  34. k_indx += 1
  35.  
  36. return cipher
  37.  
  38.  
  39. def decryptMessage(cipher):
  40. msg = ""
  41.  
  42. k_indx = 0
  43.  
  44.  
  45. msg_indx = 0
  46. msg_len = float(len(cipher))
  47. msg_lst = list(cipher)
  48.  
  49. col = len(key)
  50.  
  51. row = int(math.ceil(msg_len / col))
  52.  
  53. key_lst = sorted(list(key))
  54.  
  55.  
  56. dec_cipher = []
  57. for _ in range(row):
  58. dec_cipher += [[None] * col]
  59.  
  60. for _ in range(col):
  61. curr_idx = key.index(key_lst[k_indx])
  62.  
  63. for j in range(row):
  64. dec_cipher[j][curr_idx] = msg_lst[msg_indx]
  65. msg_indx += 1
  66. k_indx += 1
  67.  
  68. try:
  69. msg = ''.join(sum(dec_cipher, []))
  70. except TypeError:
  71. raise TypeError("This program cannot",
  72. "handle repeating words.")
  73.  
  74. null_count = msg.count('_')
  75.  
  76. if null_count > 0:
  77. return msg[: -null_count]
  78.  
  79. return msg
  80.  
  81. msg = "computer networks"
  82.  
  83. cipher = encryptMessage(msg)
  84. print("Encrypted Message: {}".
  85. format(cipher))
  86.  
  87. print("Decryped Message: {}".
  88. format(decryptMessage(cipher)))
  89.  
  90.  
Success #stdin #stdout 0.03s 9684KB
stdin
45
stdout
Encrypted Message: otno_meer_cu wsprtk_
Decryped Message: computer networks