dh.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from openid import cryptutil
  2. from openid import oidutil
  3. def strxor(x, y):
  4. if len(x) != len(y):
  5. raise ValueError('Inputs to strxor must have the same length')
  6. xor = lambda (a, b): chr(ord(a) ^ ord(b))
  7. return "".join(map(xor, zip(x, y)))
  8. class DiffieHellman(object):
  9. DEFAULT_MOD = 155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443L
  10. DEFAULT_GEN = 2
  11. def fromDefaults(cls):
  12. return cls(cls.DEFAULT_MOD, cls.DEFAULT_GEN)
  13. fromDefaults = classmethod(fromDefaults)
  14. def __init__(self, modulus, generator):
  15. self.modulus = long(modulus)
  16. self.generator = long(generator)
  17. self._setPrivate(cryptutil.randrange(1, modulus - 1))
  18. def _setPrivate(self, private):
  19. """This is here to make testing easier"""
  20. self.private = private
  21. self.public = pow(self.generator, self.private, self.modulus)
  22. def usingDefaultValues(self):
  23. return (self.modulus == self.DEFAULT_MOD and
  24. self.generator == self.DEFAULT_GEN)
  25. def getSharedSecret(self, composite):
  26. return pow(composite, self.private, self.modulus)
  27. def xorSecret(self, composite, secret, hash_func):
  28. dh_shared = self.getSharedSecret(composite)
  29. hashed_dh_shared = hash_func(cryptutil.longToBinary(dh_shared))
  30. return strxor(secret, hashed_dh_shared)