Advertisement
Trickysticks

Cryptography HW - Briscoe

Feb 25th, 2020
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. import random
  2. import math
  3.  
  4. numberList = [0, 1]
  5. resultString = ''
  6. num = 0
  7. numZero = 0
  8. numOne = 0
  9. numDigits = 0;
  10. messageSize = 1;
  11. resultDict = {}
  12. messageResultDict = {}
  13.  
  14. def calc_entropy(valueDictionary):
  15. entropy = 0
  16. for key in valueDictionary.keys():
  17. probability = valueDictionary.get(key)
  18. entropy += probability * math.log(1/probability, 2)
  19. return entropy
  20.  
  21. for i in range(1000000):
  22. num = random.choice(numberList)
  23. #print("random number chosen is: ", random.choice(numberList))
  24. resultString+=str(num)
  25. #print(resultString)
  26. numDigits = len(resultString)
  27. print("Characters in string:", '{:,}'.format(numDigits))
  28.  
  29. for element in resultString:
  30. if int(element) == 0:
  31. numZero+=1
  32. else:
  33. numOne+=1
  34. print("Number of Zeros:", '{:,}'.format(numZero))
  35. print("Number of Ones:", '{:,}'.format(numOne))
  36.  
  37. for i in range(16):
  38. messageSize = i+1
  39. numMessages = math.floor(numDigits/messageSize)
  40. resultDict = {}
  41. messageResultDict = {}
  42. iterator = 0
  43. while iterator < len(resultString):
  44. subStr = resultString[iterator:iterator+messageSize]
  45. if len(subStr)<messageSize:
  46. break
  47. if subStr in resultDict:
  48. resultDict[subStr]+=1
  49. else:
  50. resultDict[subStr]=1
  51. iterator+=messageSize
  52. #print("Message Length:", messageSize)
  53. for key in resultDict.keys():
  54. probability = resultDict.get(key)/numMessages
  55. messageResultDict[key] = probability
  56. #print("p(" + key + "):", round(probability, 3))
  57. print("Entropy of Message Length", messageSize, ":", round(calc_entropy(messageResultDict), 3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement