-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto.py
252 lines (181 loc) · 7.51 KB
/
crypto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
from hashlib import sha1
from math import ceil
from struct import Struct
import logging
from M2Crypto import EC, BIO
# Add libnacl submodule to the python path
import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'libnacl'))
import libnacl.dual
#from .util import attach_runtime_statistics
from libnacl.encode import hex_encode
_STRUCT_L = Struct(">L")
# Allow all available curves.
# Niels: 16-12-2013, if it starts with NID_
_CURVES = dict((unicode(curve), (getattr(EC, curve), "M2Crypto")) for curve in dir(EC) if curve.startswith("NID_"))
# We want to provide a few default curves. We will change these curves as new become available and
# old ones to small to provide sufficient security.
_CURVES.update({u"very-low": (EC.NID_sect163k1, "M2Crypto"),
u"low": (EC.NID_sect233k1, "M2Crypto"),
u"medium": (EC.NID_sect409k1, "M2Crypto"),
u"high": (EC.NID_sect571r1, "M2Crypto")})
# Add custom curves, not provided by M2Crypto
_CURVES.update({u'curve25519': (None, "libnacl")})
logger = logging.getLogger(__name__)
class DispersyCrypto(object):
@property
def security_levels(self):
"""
Returns the different security levels supported by this crypto class
@rtype: [unicode]
"""
raise NotImplementedError()
def generate_key(self, security_level):
"""
Generate a new key using the specified security_level
@param security_level: Level of security, supported levels can be obtained using .security_levels.
@type security_level: unicode
@rtype key
"""
raise NotImplementedError()
def key_to_bin(self, key):
"Convert a key to the binary format."
raise NotImplementedError()
def key_to_hash(self, key):
"Get a hash representation from a key."
raise NotImplementedError()
def key_from_public_bin(self, string):
"Convert a public key stored in the binary format to a key object."
raise NotImplementedError()
def key_from_private_bin(self, string):
"Convert a public/private keypair stored in the binary format to a key object."
raise NotImplementedError()
def is_valid_public_bin(self, string):
"Verify if this binary string contains a public key."
raise NotImplementedError()
def is_valid_private_bin(self, string):
"Verify if this binary string contains a public/private keypair."
raise NotImplementedError()
def is_valid_signature(self, key, string, signature):
"Verify if the signature matches the one generated by key/string pair."
raise NotImplementedError()
def create_signature(self, key, string):
"Create a signature using this key for this string."
raise NotImplementedError()
def get_signature_length(self, key):
"Get the length of a signature created using this key in bytes."
raise NotImplementedError()
class ECCrypto(DispersyCrypto):
"""
A crypto object which provides a layer between Dispersy and low level eccrypographic features.
Most methods are implemented by:
@author: Boudewijn Schoon
@organization: Technical University Delft
@contact: dispersy@frayja.com
However since then, most functionality was completely rewritten by:
@author: Niels Zeilemaker
"""
#def _progress(self, *args):
#"Called when no feedback needs to be given."
#pass
@property
def security_levels(self):
"""
Returns the names of all available curves.
@rtype: [unicode]
"""
return _CURVES.keys()
def generate_key(self, security_level):
"""
Generate a new Elliptic Curve object with a new public / private key pair.
Security can be u'low', u'medium', or u'high' depending on how secure you need your Elliptic
Curve to be. Currently these values translate into:
- very-low: NID_sect163k1 ~42 byte signatures
- low: NID_sect233k1 ~60 byte signatures
- medium: NID_sect409k1 ~104 byte signatures
- high: NID_sect571r1 ~144 byte signatures
Besides these predefined curves, all other curves provided by M2Crypto are also available. For
a full list of available curves, see ec_get_curves().
@param security_level: Level of security {u'very-low', u'low', u'medium', or u'high'}.
@type security_level: unicode
"""
assert isinstance(security_level, unicode)
assert security_level in _CURVES
curve = _CURVES[security_level]
return M2CryptoSK(curve[0])
def key_to_bin(self, ec):
"Convert the key to a binary format."
assert isinstance(ec, DispersyKey), ec
return ec.key_to_bin()
def key_to_hash(self, ec):
"Get a hash representation from a key."
assert isinstance(ec, DispersyKey), ec
return ec.key_to_hash()
def key_from_public_bin(self, string):
"Get the EC from a public key in binary format."
#if string.startswith("LibNaCLPK:"):
#return LibNaCLPK(string[10:])
return M2CryptoPK(keystring=string)
def create_signature(self, ec, data):
"""
Returns the signature of DIGEST made using EC.
"""
assert isinstance(ec, DispersyKey), ec
assert isinstance(data, str), type(data)
return ec.signature(data)
class DispersyKey(object):
def pub(self):
raise NotImplementedError()
def has_secret_key(self):
raise NotImplementedError()
def key_to_bin(self):
raise NotImplementedError()
def key_to_hash(self):
if self.has_secret_key():
return sha1(self.pub().key_to_bin()).digest()
return sha1(self.key_to_bin()).digest()
class M2CryptoPK(DispersyKey):
def __init__(self, ec_pub=None, keystring=None):
if ec_pub:
self.ec = ec_pub
elif keystring:
self.ec = self.key_from_pem("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n" % keystring.encode("BASE64"))
def pub(self):
return self
def has_secret_key(self):
return False
def pem_to_bin(self, pem):
"""
Convert a key in the PEM format into a key in the binary format.
@note: Enrcypted pem's are NOT supported and will silently fail.
"""
return "".join(pem.split("\n")[1:-2]).decode("BASE64")
def key_to_pem(self):
"Convert a key to the PEM format."
bio = BIO.MemoryBuffer()
self.ec.save_pub_key_bio(bio)
return bio.read_all()
def key_from_pem(self, pem):
"Get the EC from a public PEM."
return EC.load_pub_key_bio(BIO.MemoryBuffer(pem))
def key_to_bin(self):
return self.pem_to_bin(self.key_to_pem())
class M2CryptoSK(M2CryptoPK):
def __init__(self, curve=None, keystring=None, filename=None):
if curve:
self.ec = EC.gen_params(curve)
self.ec.gen_key()
def pub(self):
return M2CryptoPK(ec_pub=self.ec.pub())
#def has_secret_key(self):
#return True
def signature(self, msg):
length = int(ceil(len(self.ec) / 8.0))
digest = sha1(msg).digest()
mpi_r, mpi_s = self.ec.sign_dsa(digest)
length_r, = _STRUCT_L.unpack_from(mpi_r)
r = mpi_r[-min(length, length_r):]
length_s, = _STRUCT_L.unpack_from(mpi_s)
s = mpi_s[-min(length, length_s):]
return "".join(("\x00" * (length - len(r)), r, "\x00" * (length - len(s)), s))