xor


SUBMITTED BY: franek4700

DATE: Jan. 26, 2017, 6:04 a.m.

FORMAT: Text only

SIZE: 700 Bytes

HITS: 763

  1. from os import urandom
  2. def u_ord(c):
  3. """Adapt `ord(c)` for Python 2 or 3"""
  4. return ord(str(c)[0:1])
  5. def genkey(length):
  6. """Generate key"""
  7. return urandom(length)
  8. def xor_strings(s, t):
  9. """xor two strings together"""
  10. return "".join(chr(u_ord(a) ^ u_ord(b)) for a, b in zip(s, t))
  11. message = 'This is a secret message'
  12. print ('message:', message)
  13. key = genkey(len(message))
  14. print ('key:', key)
  15. cipherText = xor_strings(message, key)
  16. print ('cipherText:', cipherText)
  17. print ('decrypted:', xor_strings(cipherText, key))
  18. # verify
  19. if xor_strings(cipherText, key) == message:
  20. print ('Unit test passed')
  21. else:
  22. print ('Unit test failed')

comments powered by Disqus