/gdata/tlslite/utils/PyCrypto_RSAKey.py

http://radioappz.googlecode.com/ · Python · 61 lines · 48 code · 12 blank · 1 comment · 9 complexity · 8758ed3f01e926752ac14c95f7be3fb1 MD5 · raw file

  1. """PyCrypto RSA implementation."""
  2. from cryptomath import *
  3. from RSAKey import *
  4. from Python_RSAKey import Python_RSAKey
  5. if pycryptoLoaded:
  6. from Crypto.PublicKey import RSA
  7. class PyCrypto_RSAKey(RSAKey):
  8. def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
  9. if not d:
  10. self.rsa = RSA.construct( (n, e) )
  11. else:
  12. self.rsa = RSA.construct( (n, e, d, p, q) )
  13. def __getattr__(self, name):
  14. return getattr(self.rsa, name)
  15. def hasPrivateKey(self):
  16. return self.rsa.has_private()
  17. def hash(self):
  18. return Python_RSAKey(self.n, self.e).hash()
  19. def _rawPrivateKeyOp(self, m):
  20. s = numberToString(m)
  21. byteLength = numBytes(self.n)
  22. if len(s)== byteLength:
  23. pass
  24. elif len(s) == byteLength-1:
  25. s = '\0' + s
  26. else:
  27. raise AssertionError()
  28. c = stringToNumber(self.rsa.decrypt((s,)))
  29. return c
  30. def _rawPublicKeyOp(self, c):
  31. s = numberToString(c)
  32. byteLength = numBytes(self.n)
  33. if len(s)== byteLength:
  34. pass
  35. elif len(s) == byteLength-1:
  36. s = '\0' + s
  37. else:
  38. raise AssertionError()
  39. m = stringToNumber(self.rsa.encrypt(s, None)[0])
  40. return m
  41. def writeXMLPublicKey(self, indent=''):
  42. return Python_RSAKey(self.n, self.e).write(indent)
  43. def generate(bits):
  44. key = PyCrypto_RSAKey()
  45. def f(numBytes):
  46. return bytesToString(getRandomBytes(numBytes))
  47. key.rsa = RSA.generate(bits, f)
  48. return key
  49. generate = staticmethod(generate)