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