1
2
3
4 """OpenSSL/M2Crypto RSA implementation."""
5
6 from .cryptomath import *
7
8 from .rsakey import *
9 from .python_rsakey import Python_RSAKey
10
11
12
13 -def password_callback(v, prompt1='Enter private key passphrase:',
14 prompt2='Verify passphrase:'):
15 from getpass import getpass
16 while 1:
17 try:
18 p1=getpass(prompt1)
19 if v:
20 p2=getpass(prompt2)
21 if p1==p2:
22 break
23 else:
24 break
25 except KeyboardInterrupt:
26 return None
27 return p1
28
29
30 if m2cryptoLoaded:
33 self.rsa = None
34 self._hasPrivateKey = False
35 if (n and not e) or (e and not n):
36 raise AssertionError()
37 if n and e:
38 self.rsa = m2.rsa_new()
39 m2.rsa_set_n(self.rsa, numberToMPI(n))
40 m2.rsa_set_e(self.rsa, numberToMPI(e))
41
43 if self.rsa:
44 m2.rsa_free(self.rsa)
45
47 if name == 'e':
48 if not self.rsa:
49 return 0
50 return mpiToNumber(m2.rsa_get_e(self.rsa))
51 elif name == 'n':
52 if not self.rsa:
53 return 0
54 return mpiToNumber(m2.rsa_get_n(self.rsa))
55 else:
56 raise AttributeError
57
59 return self._hasPrivateKey
60
66
72
74
75 - def write(self, password=None):
76 bio = m2.bio_new(m2.bio_s_mem())
77 if self._hasPrivateKey:
78 if password:
79 def f(v): return password
80 m2.rsa_write_key(self.rsa, bio, m2.des_ede_cbc(), f)
81 else:
82 def f(): pass
83 m2.rsa_write_key_no_cipher(self.rsa, bio, f)
84 else:
85 if password:
86 raise AssertionError()
87 m2.rsa_write_pub_key(self.rsa, bio)
88 s = m2.bio_read(bio, m2.bio_ctrl_pending(bio))
89 m2.bio_free(bio)
90 return s
91
93 key = OpenSSL_RSAKey()
94 def f():pass
95 key.rsa = m2.rsa_generate_key(bits, 3, f)
96 key._hasPrivateKey = True
97 return key
98 generate = staticmethod(generate)
99
100 - def parse(s, passwordCallback=None):
101
102 start = s.find("-----BEGIN ")
103 if start == -1:
104 raise SyntaxError()
105 s = s[start:]
106 if s.startswith("-----BEGIN "):
107 if passwordCallback==None:
108 callback = password_callback
109 else:
110 def f(v, prompt1=None, prompt2=None):
111 return passwordCallback()
112 callback = f
113 bio = m2.bio_new(m2.bio_s_mem())
114 try:
115 m2.bio_write(bio, s)
116 key = OpenSSL_RSAKey()
117
118 if s.startswith("-----BEGIN RSA PRIVATE KEY-----"):
119 def f():pass
120 key.rsa = m2.rsa_read_key(bio, callback)
121 if key.rsa == None:
122 raise SyntaxError()
123 key._hasPrivateKey = True
124
125 elif s.startswith("-----BEGIN PRIVATE KEY-----"):
126 def f():pass
127 key.rsa = m2.pkey_read_pem(bio, callback)
128
129
130
131
132
133
134
135 if key.rsa == None:
136 raise SyntaxError()
137 key.rsa = m2.pkey_get1_rsa(key.rsa)
138 if key.rsa == None:
139 raise SyntaxError()
140 key._hasPrivateKey = True
141 elif s.startswith("-----BEGIN PUBLIC KEY-----"):
142 key.rsa = m2.rsa_read_pub_key(bio)
143 if key.rsa == None:
144 raise SyntaxError()
145 key._hasPrivateKey = False
146 else:
147 raise SyntaxError()
148 return key
149 finally:
150 m2.bio_free(bio)
151 else:
152 raise SyntaxError()
153
154 parse = staticmethod(parse)
155