Hacking Secret Ciphers with Python

(Ann) #1

328 http://inventwithpython.com/hacking


Email questions to the author: [email protected]







  1. def getUsefulFactors(num):


  2. Returns a list of useful factors of num. By "useful" we mean factors




  3. less than MAX_KEY_LENGTH + 1. For example, getUsefulFactors(144)




  4. returns [2, 72, 3, 48, 4, 36, 6, 24, 8, 18, 9, 16, 12]





  5. if num < 2:

  6. return [] # numbers less than 2 have no useful factors



  7. factors = [] # the list of factors found




  8. When finding factors, you only need to check the integers up to




  9. MAX_KEY_LENGTH.



  10. for i in range(2, MAX_KEY_LENGTH + 1): # don't test 1

  11. if num % i == 0:

  12. factors.append(i)

  13. factors.append(int(num / i))

  14. if 1 in factors:

  15. factors.remove(1)

  16. return list(set(factors))





  17. def getItemAtIndexOne(x):

  18. return x[1]





  19. def getMostCommonFactors(seqFactors):


  20. First, get a count of how many times a factor occurs in seqFactors.



  21. factorCounts = {} # key is a factor, value is how often if occurs




  22. seqFactors keys are sequences, values are lists of factors of the




  23. spacings. seqFactors has a value like: {'GFD': [2, 3, 4, 6, 9, 12,




  24. 18, 23, 36, 46, 69, 92, 138, 207], 'ALW': [2, 3, 4, 6, ...], ...}



  25. for seq in seqFactors:

  26. factorList = seqFactors[seq]

  27. for factor in factorList:

  28. if factor not in factorCounts:

  29. factorCounts[factor] = 0

  30. factorCounts[factor] += 1




  31. Second, put the factor and its count into a tuple, and make a list




  32. of these tuples so we can sort them.



  33. factorsByCount = []

  34. for factor in factorCounts:


  35. exclude factors larger than MAX_KEY_LENGTH



Free download pdf