Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import secrets
  2. import string
  3. from collections import Counter
  4.  
  5.  
  6. def normalize(text):
  7. return ''.join([c for c in text.upper() if c.isalpha()])
  8.  
  9.  
  10. def index_of_coincidence(text):
  11. counter = Counter(text)
  12. N = sum(counter.values())
  13. IC = 0
  14.  
  15. for _, freq in counter.items():
  16. IC += freq * (freq - 1)
  17.  
  18. return IC / (N*(N-1))
  19.  
  20.  
  21. def generate_key(key_length):
  22. return [secrets.randbelow(26) for _ in range(key_length)]
  23.  
  24.  
  25. def polyalphabetic_rotation(plaintext: str, key):
  26. ciphertext = ''
  27. for idx, char in enumerate(plaintext.lower()):
  28. k = key[idx % (len(key))]
  29. p = ord(char) - ord('a')
  30. c = (p+k) % 26
  31. ciphertext += chr(c + ord('a'))
  32.  
  33. return ciphertext
  34.  
  35.  
  36. if __name__ == "__main__":
  37. text = normalize('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
  38.  
  39. for length in range(1, 16):
  40. ic = index_of_coincidence(polyalphabetic_rotation(text, generate_key(length)))
  41. print(length, ic, sep='\t')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement