1
2
3
4 """Pure-Python RSA implementation."""
5
6 from .cryptomath import *
7 from .asn1parser import ASN1Parser
8 from .rsakey import *
9 from .pem import *
10
12 - def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
13 if (n and not e) or (e and not n):
14 raise AssertionError()
15 self.n = n
16 self.e = e
17 self.d = d
18 self.p = p
19 self.q = q
20 self.dP = dP
21 self.dQ = dQ
22 self.qInv = qInv
23 self.blinder = 0
24 self.unblinder = 0
25
28
30
31 if not self.blinder:
32 self.unblinder = getRandomNumber(2, self.n)
33 self.blinder = powMod(invMod(self.unblinder, self.n), self.e,
34 self.n)
35
36
37 m = (m * self.blinder) % self.n
38
39
40 c = self._rawPrivateKeyOpHelper(m)
41
42
43 c = (c * self.unblinder) % self.n
44
45
46 self.blinder = (self.blinder * self.blinder) % self.n
47 self.unblinder = (self.unblinder * self.unblinder) % self.n
48
49
50 return c
51
52
54
55
56
57
58 s1 = powMod(m, self.dP, self.p)
59 s2 = powMod(m, self.dQ, self.q)
60 h = ((s1 - s2) * self.qInv) % self.p
61 c = s2 + self.q * h
62 return c
63
65 m = powMod(c, self.e, self.n)
66 return m
67
69
71 key = Python_RSAKey()
72 p = getRandomPrime(bits//2, False)
73 q = getRandomPrime(bits//2, False)
74 t = lcm(p-1, q-1)
75 key.n = p * q
76 key.e = 65537
77 key.d = invMod(key.e, t)
78 key.p = p
79 key.q = q
80 key.dP = key.d % (p-1)
81 key.dQ = key.d % (q-1)
82 key.qInv = invMod(q, p)
83 return key
84 generate = staticmethod(generate)
85
97 parsePEM = staticmethod(parsePEM)
98
100 p = ASN1Parser(bytes)
101
102
103 version = p.getChild(0).value
104 if bytesToNumber(version) != 0:
105 raise SyntaxError("Unrecognized PKCS8 version")
106
107
108
109 algIdent = p.getChild(1)
110 seqLen = algIdent.getChildCount()
111
112 oid = algIdent.getChild(0)
113 if list(oid.value) == [42, 134, 72, 134, 247, 13, 1, 1, 1]:
114 keyType = "rsa"
115 elif list(oid.value) == [42, 134, 72, 134, 247, 13, 1, 1, 10]:
116 keyType = "rsa-pss"
117 else:
118 raise SyntaxError("Unrecognized AlgorithmIdentifier: {0}"
119 .format(list(oid.value)))
120
121
122 if keyType == "rsa":
123 if seqLen != 2:
124 raise SyntaxError("Missing parameters for RSA algorithm ID")
125 parameters = algIdent.getChild(1)
126 if parameters.value != bytearray(0):
127 raise SyntaxError("RSA parameters are not NULL")
128 else:
129 pass
130
131 if seqLen > 2:
132 raise SyntaxError("Invalid encoding of AlgorithmIdentifier")
133
134
135 privateKeyP = p.getChild(2)
136
137
138 privateKeyP = ASN1Parser(privateKeyP.value)
139
140 return Python_RSAKey._parseASN1PrivateKey(privateKeyP)
141 _parsePKCS8 = staticmethod(_parsePKCS8)
142
146 _parseSSLeay = staticmethod(_parseSSLeay)
147
161 _parseASN1PrivateKey = staticmethod(_parseASN1PrivateKey)
162