OLD | NEW |
| 1 # Author: Trevor Perrin |
| 2 # See the LICENSE file for legal information regarding use of this file. |
| 3 |
1 """PyCrypto RSA implementation.""" | 4 """PyCrypto RSA implementation.""" |
2 | 5 |
3 from cryptomath import * | 6 from .cryptomath import * |
4 | 7 |
5 from rsakey import * | 8 from .rsakey import * |
6 from python_rsakey import Python_RSAKey | 9 from .python_rsakey import Python_RSAKey |
7 | 10 |
8 if pycryptoLoaded: | 11 if pycryptoLoaded: |
9 | 12 |
10 from Crypto.PublicKey import RSA | 13 from Crypto.PublicKey import RSA |
11 | 14 |
12 class PyCrypto_RSAKey(RSAKey): | 15 class PyCrypto_RSAKey(RSAKey): |
13 def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): | 16 def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): |
14 if not d: | 17 if not d: |
15 self.rsa = RSA.construct( (n, e) ) | 18 self.rsa = RSA.construct( (n, e) ) |
16 else: | 19 else: |
17 self.rsa = RSA.construct( (n, e, d, p, q) ) | 20 self.rsa = RSA.construct( (n, e, d, p, q) ) |
18 | 21 |
19 def __getattr__(self, name): | 22 def __getattr__(self, name): |
20 return getattr(self.rsa, name) | 23 return getattr(self.rsa, name) |
21 | 24 |
22 def hasPrivateKey(self): | 25 def hasPrivateKey(self): |
23 return self.rsa.has_private() | 26 return self.rsa.has_private() |
24 | 27 |
25 def hash(self): | |
26 return Python_RSAKey(self.n, self.e).hash() | |
27 | |
28 def _rawPrivateKeyOp(self, m): | 28 def _rawPrivateKeyOp(self, m): |
29 s = numberToString(m) | 29 s = bytes(numberToByteArray(m, numBytes(self.n))) |
30 byteLength = numBytes(self.n) | 30 c = bytesToNumber(bytearray(self.rsa.decrypt((s,)))) |
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 | 31 return c |
39 | 32 |
40 def _rawPublicKeyOp(self, c): | 33 def _rawPublicKeyOp(self, c): |
41 s = numberToString(c) | 34 s = bytes(numberToByteArray(c, numBytes(self.n))) |
42 byteLength = numBytes(self.n) | 35 m = bytesToNumber(bytearray(self.rsa.encrypt(s, None)[0])) |
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 | 36 return m |
51 | 37 |
52 def writeXMLPublicKey(self, indent=''): | |
53 return Python_RSAKey(self.n, self.e).write(indent) | |
54 | |
55 def generate(bits): | 38 def generate(bits): |
56 key = PyCrypto_RSAKey() | 39 key = PyCrypto_RSAKey() |
57 def f(numBytes): | 40 def f(numBytes): |
58 return bytesToString(getRandomBytes(numBytes)) | 41 return bytes(getRandomBytes(numBytes)) |
59 key.rsa = RSA.generate(bits, f) | 42 key.rsa = RSA.generate(bits, f) |
60 return key | 43 return key |
61 generate = staticmethod(generate) | 44 generate = staticmethod(generate) |
OLD | NEW |