1
2
3
4 """Pure-Python RSA implementation."""
5
6 from .cryptomath import *
7 from .asn1parser import ASN1Parser
8 from .rsakey import *
9
11 - def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
12 if (n and not e) or (e and not n):
13 raise AssertionError()
14 self.n = n
15 self.e = e
16 self.d = d
17 self.p = p
18 self.q = q
19 self.dP = dP
20 self.dQ = dQ
21 self.qInv = qInv
22 self.blinder = 0
23 self.unblinder = 0
24
27
29
30 if not self.blinder:
31 self.unblinder = getRandomNumber(2, self.n)
32 self.blinder = powMod(invMod(self.unblinder, self.n), self.e,
33 self.n)
34
35
36 m = (m * self.blinder) % self.n
37
38
39 c = self._rawPrivateKeyOpHelper(m)
40
41
42 c = (c * self.unblinder) % self.n
43
44
45 self.blinder = (self.blinder * self.blinder) % self.n
46 self.unblinder = (self.unblinder * self.unblinder) % self.n
47
48
49 return c
50
51
53
54
55
56
57 s1 = powMod(m, self.dP, self.p)
58 s2 = powMod(m, self.dQ, self.q)
59 h = ((s1 - s2) * self.qInv) % self.p
60 c = s2 + self.q * h
61 return c
62
64 m = powMod(c, self.e, self.n)
65 return m
66
68
70 key = Python_RSAKey()
71 p = getRandomPrime(bits//2, False)
72 q = getRandomPrime(bits//2, False)
73 t = lcm(p-1, q-1)
74 key.n = p * q
75 key.e = 65537L
76 key.d = invMod(key.e, t)
77 key.p = p
78 key.q = q
79 key.dP = key.d % (p-1)
80 key.dQ = key.d % (q-1)
81 key.qInv = invMod(q, p)
82 return key
83 generate = staticmethod(generate)
84
86 """Parse a string containing a <privateKey> or <publicKey>, or
87 PEM-encoded key."""
88
89 start = s.find("-----BEGIN PRIVATE KEY-----")
90 if start != -1:
91 end = s.find("-----END PRIVATE KEY-----")
92 if end == -1:
93 raise SyntaxError("Missing PEM Postfix")
94 s = s[start+len("-----BEGIN PRIVATE KEY -----") : end]
95 bytes = base64ToBytes(s)
96 return Python_RSAKey._parsePKCS8(bytes)
97 else:
98 start = s.find("-----BEGIN RSA PRIVATE KEY-----")
99 if start != -1:
100 end = s.find("-----END RSA PRIVATE KEY-----")
101 if end == -1:
102 raise SyntaxError("Missing PEM Postfix")
103 s = s[start+len("-----BEGIN RSA PRIVATE KEY -----") : end]
104 bytes = base64ToBytes(s)
105 return Python_RSAKey._parseSSLeay(bytes)
106 raise SyntaxError("Missing PEM Prefix")
107 parsePEM = staticmethod(parsePEM)
108
110 p = ASN1Parser(bytes)
111
112 version = p.getChild(0).value[0]
113 if version != 0:
114 raise SyntaxError("Unrecognized PKCS8 version")
115
116 rsaOID = p.getChild(1).value
117 if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]:
118 raise SyntaxError("Unrecognized AlgorithmIdentifier")
119
120
121 privateKeyP = p.getChild(2)
122
123
124 privateKeyP = ASN1Parser(privateKeyP.value)
125
126 return Python_RSAKey._parseASN1PrivateKey(privateKeyP)
127 _parsePKCS8 = staticmethod(_parsePKCS8)
128
132 _parseSSLeay = staticmethod(_parseSSLeay)
133
147 _parseASN1PrivateKey = staticmethod(_parseASN1PrivateKey)
148