Cryptography With Python 简明教程

Testing of Simple Substitution Cipher

在本章中,我们将专注于使用各种方法测试替换密码,这有助于生成随机字符串,如下所示 −

import random, string, substitution
def main():
   for i in range(1000):
      key = substitution.getRandomKey()
      message = random_string()
      print('Test %s: String: "%s.."' % (i + 1, message[:50]))
      print("Key: " + key)
      encrypted = substitution.translateMessage(message, key, 'E')
      decrypted = substitution.translateMessage(encrypted, key, 'D')

      if decrypted != message:
         print('ERROR: Decrypted: "%s" Key: %s' % (decrypted, key))
         sys.exit()
      print('Substutition test passed!')

def random_string(size = 5000, chars = string.ascii_letters + string.digits):
   return ''.join(random.choice(chars) for _ in range(size))
if __name__ == '__main__':
   main()

Output

您可以观察到作为随机生成字符串的输出,这有助于生成随机明文消息,如下所示 −

strings

测试成功完成之后,我们可以观察到输出消息 “ Substitution test passed!.

substitution

因此,您可以以系统的方式破解替换密码。