-
Notifications
You must be signed in to change notification settings - Fork 6
/
crypto.py
379 lines (277 loc) · 7.44 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# -*- coding: utf-8 -*-
"""
Various symmetric and asymmetric crypto routines.
"""
from __future__ import absolute_import, print_function, unicode_literals
import pyscrypt
import base58
import hashlib
import libnacl.public
import libnacl.secret
# The public key used for verifying peer tokens which are the identify
# certificates.
TOKEN_PUBLIC_KEY = ''
XID_PREFIX = b'\x5f'
KEY_PREFIX = b'\xba' # prefix for public key string
SECRET_PREFIX = b'\xff' # prefix for secret key string
FINGER_PREFIX = b'\xef'
def generate_keypair(sk=None):
"""
Generate a random key pair.
:return: the (public key, secret key) tuple
"""
if sk:
keypair = libnacl.public.SecretKey(sk=sk)
else:
keypair = libnacl.public.SecretKey()
return keypair.pk, keypair.sk
def generate_symmetric_key():
"""
Generate a random key for symmetric encryption.
:return:
"""
box = libnacl.secret.SecretBox()
return box.sk
def key_to_xid(key):
"""
Generate an address from a public key.
:param key: the 32-byte byte string.
:return:
"""
sha256 = hashlib.sha256()
sha256.update(XID_PREFIX)
sha256.update(key)
sum = sha256.digest()
addr = XID_PREFIX + key + sum[:2]
return base58.b58encode(addr)
def xid_to_key(xid):
"""
Retrieve the key from an XID.
:param xid:
:return:
"""
val = base58.b58decode(xid)
if len(val) != 35:
return None
prefix = val[0]
if prefix != XID_PREFIX:
return None
key = val[1:33]
sha256 = hashlib.sha256()
sha256.update(XID_PREFIX)
sha256.update(key)
s = sha256.digest()
if val[-2:] != s[:2]:
return None
return key
def validate_xid(addr):
"""
Check if the provided XID is valid or not.
:param addr: XID in base58 string.
:return:
"""
val = base58.b58decode(addr)
if len(val) != 35:
return False
prefix = val[0]
if prefix != XID_PREFIX:
return False
sha256 = hashlib.sha256()
sha256.update(XID_PREFIX)
sha256.update(val[1:33])
s = sha256.digest()
if val[-2:] != s[:2]:
return False
return True
def key_to_fingerprint(key):
""" Fingerprint is used to uniquely identify an entity without exposing
extra information.
:param key: the public key
:return:
"""
sha256 = hashlib.sha256()
sha256.update(key)
key_hash = sha256.digest()
ripemd = hashlib.new('ripemd')
ripemd.update(key_hash)
key_hash = ripemd.digest()
sha256 = hashlib.sha256()
sha256.update(FINGER_PREFIX)
sha256.update(key_hash)
checksum = sha256.digest()
result = FINGER_PREFIX+key_hash+checksum[:4]
return base58.b58encode(result)
def validate_fingerprint(fingerprint):
val = base58.b58decode(fingerprint)
if len(val) != 25:
return False
prefix = val[0]
if prefix != FINGER_PREFIX:
return False
key_hash = val[1:21]
sha256 = hashlib.sha256()
sha256.update(FINGER_PREFIX)
sha256.update(key_hash)
given_checksum = sha256.digest()[:4]
expected_checksum = val[-4:]
if expected_checksum != given_checksum:
return False
return True
def xid_to_fingerprint(address):
key = xid_to_key(address)
if key:
return key_to_fingerprint(key)
else:
return None
def key_to_peer_id(key):
sha256 = hashlib.sha256()
sha256.update(key)
key_hash = sha256.digest()
ripemd = hashlib.new('ripemd')
ripemd.update(key_hash)
return ripemd.digest()
def calc_session_key(pk, sk):
"""
Calculate the session key from a public key and secret key.
:param pk: the counterpart's public key.
:param sk: the own private key
:return:
"""
return libnacl.crypto_box_beforenm(pk, sk)
def secret_key_encrypt(sk, plaindata):
"""
Encrypt a chunk of data with secret key symmetric encryption.
:param sk:
:param plaindata:
:return:
"""
box = libnacl.secret.SecretBox(sk)
return box.encrypt(plaindata)
def secret_key_decrypt(sk, encrypted):
box = libnacl.secret.SecretBox(sk)
return box.decrypt(encrypted)
def secret_key_box(sk):
return libnacl.secret.SecretBox(sk)
def public_key_encrypt(sender_sk, receiver_pk, plaintext):
sender_box = libnacl.public.Box(sender_sk, receiver_pk)
return sender_box.encrypt(plaintext)
def public_key_decrypt(receiver_sk, sender_pk, ciphertext):
receiver_box = libnacl.public.Box(receiver_sk, sender_pk)
return receiver_box.decrypt(ciphertext)
def public_key_box(sk, pk):
return libnacl.public.Box(sk, pk)
def derive_secret_key(password=None, salt=None):
"""
Derives secret key from password and salt combination with Scrypt.
:param password:
:param salt:
:return:
"""
hash = pyscrypt.hash(password=password,
salt=salt,
N=1024,
r=1,
p=1,
dkLen=32)
return hash
def secret_key_to_xid(sk):
"""
Derives XID from a secret key.
:param sk:
:return:
"""
keyobj = libnacl.public.SecretKey(sk=sk)
pk = keyobj.pk
return key_to_xid(pk)
def secret_to_string(key):
"""
Converts a secret key to its string form
:param key: the secret key
:return: a string equivalent to the secret key
"""
sha256 = hashlib.sha256()
sha256.update(SECRET_PREFIX)
sha256.update(key)
sum = sha256.digest()
result = SECRET_PREFIX + key + sum[:2]
return base58.b58encode(result)
def string_to_secret(sk_str):
val = base58.b58decode(sk_str)
if len(val) != 35:
return None
prefix = val[0]
if prefix != SECRET_PREFIX:
return None
key = val[1:33]
sha256 = hashlib.sha256()
sha256.update(SECRET_PREFIX)
sha256.update(key)
s = sha256.digest()
if val[-2:] != s[:2]:
return None
return key
def validate_secret_string(sk_str):
"""
Validates a given public key string.
:param sk_str:
:return:
"""
val = base58.b58decode(sk_str)
if len(val) != 35:
return False
prefix = val[0]
if prefix != SECRET_PREFIX:
return False
sha256 = hashlib.sha256()
sha256.update(SECRET_PREFIX)
sha256.update(val[1:33])
s = sha256.digest()
if val[-2:] != s[:2]:
return False
return True
def key_to_string(key):
"""
Converts a public key to its string form
:param key: the public key
:return:
"""
sha256 = hashlib.sha256()
sha256.update(KEY_PREFIX)
sha256.update(key)
sum = sha256.digest()
result = KEY_PREFIX + key + sum[:2]
return base58.b58encode(result)
def string_to_key(pk_str):
val = base58.b58decode(pk_str)
if len(val) != 35:
return None
prefix = val[0]
if prefix != KEY_PREFIX:
return None
key = val[1:33]
sha256 = hashlib.sha256()
sha256.update(KEY_PREFIX)
sha256.update(key)
s = sha256.digest()
if val[-2:] != s[:2]:
return None
return key
def validate_key_string(pk_str):
"""
Validates a given public key string.
:param sk_str:
:return:
"""
val = base58.b58decode(pk_str)
if len(val) != 35:
return False
prefix = val[0]
if prefix != KEY_PREFIX:
return False
sha256 = hashlib.sha256()
sha256.update(KEY_PREFIX)
sha256.update(val[1:33])
s = sha256.digest()
if val[-2:] != s[:2]:
return False
return True