-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnaclHelper-to-be-deprecated.js
582 lines (550 loc) · 19.9 KB
/
naclHelper-to-be-deprecated.js
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
// import { blake2b } from 'blakejs'
// import {
// // secret key encryption
// naclDecrypt as naclDecrypt1,
// naclEncrypt as naclEncrypt1,
// naclKeypairFromString,
// naclKeypairFromSeed,
// naclKeypairFromSecret,
// // box encrypt
// naclBoxKeypairFromSecret,
// naclSeal,
// naclOpen,
// // singature
// naclSign,
// naclVerify,
// randomAsU8a,
// } from '@polkadot/util-crypto'
// import { generateHash, isArr, isHex, isMap, isObj, isUint8Arr, objCopy } from './utils'
// import {
// bytesToHex,
// hexToBytes,
// ss58Encode,
// u8aToStr,
// strToU8a,
// } from './convert'
// /**
// * @name decrypt
// * @summary decrypted a message encrypted using TweetNacl Box depryption (open) mechanism
// *
// * @param {String|Uint8Array} sealed data to encrypt
// * @param {String|Uint8Array} nonce
// * @param {String|Uint8Array} senderPublicKey
// * @param {String|Uint8Array} recipientSecretKey
// * @param {Boolean}
// *
// * @returns {String|Uint8Array} decrypted message
// */
// export const decrypt = (sealed, nonce, senderPublicKey, recipientSecretKey, asString = true) => {
// const decrypted = naclOpen(
// hexToBytes(sealed),
// hexToBytes(nonce),
// hexToBytes(senderPublicKey),
// hexToBytes(recipientSecretKey),
// )
// if (!decrypted) return decrypted
// return !asString
// ? decrypted
// : u8aToStr(decrypted)
// }
// /**
// * @name decryptObj
// * @summary recursively decrypt objects encrypted using `encryptObj()` function.
// * @description see see `encryptObj()` function documentation for examples
// *
// * @param {Object} obj data object to decrypt
// * @param {String|Uint8Array} senderPublicKey
// * @param {String|Uint8Array} recipientSecretKey
// * @param {Array} keys (optional) `obj` property names, to be decrypted.
// * If valid array, unlisted properties will not be decrypted.
// * g9i, will attempt to decrypt all properties.
// * See examples for different usage cases.
// * @param {Boolean} asString (optional) whether to convert result bytes to string.
// * Default: true
// *
// * @returns {Object} decrypted object
// */
// export const decryptObj = (obj, senderPublicKey, recipientSecretKey, keys, asString = true) => {
// if (!isObj(obj)) return
// const result = { ...obj }
// const isBox = !!senderPublicKey
// const open = isBox
// ? decrypt
// : secretBoxDecrypt
// const validKeys = !isArr(keys)
// // decrypt all properties
// ? Object.keys(result)
// // decrypt only specified properties
// : keys.filter(k => result.hasOwnProperty(k))
// for (let i = 0; i < validKeys.length; i++) {
// const key = validKeys[i]
// const value = result[key]
// if (!obj.hasOwnProperty(key)) continue
// // value is an object => recursively decrypt
// if (isObj(value)) {
// const childKeyPrefix = `${key}.`
// const childKeys = validKeys
// .filter(k => k.startsWith(childKeyPrefix))
// // get rid of prefix
// .map(k => k.replace(new RegExp(childKeyPrefix), ''))
// result[key] = decryptObj(
// value,
// senderPublicKey,
// recipientSecretKey,
// childKeys.length > 0
// ? childKeys // decrypt only specified child keys
// : null, // decrypt all child keys
// asString,
// )
// continue
// }
// const bytes = hexToBytes(value)
// if (!bytes || bytes.length <= 24) throw new Error('Decryption failed')
// const args = [
// new Uint8Array(bytes.slice(24)),
// new Uint8Array(bytes.slice(0, 24)),
// ...[isBox && senderPublicKey].filter(Boolean),
// recipientSecretKey,
// asString,
// ]
// result[key] = open(...args)
// }
// return result
// }
// /**
// * @name encrypt
// * @description encrypt a message using TweetNacl Box seal encryption
// *
// * @param {String|Uint8Array} message data to encrypt. String|Uint8Array
// * @param {String|Uint8Array} senderSecretKey
// * @param {String|Uint8Array} recipientPublicKey
// * @param {String|Uint8Array} nonce (optional) if undefined, will generate new nonce
// * @param {Boolean} asHex whether to convert to hex or reutrn Uint8Array
// *
// * @returns Object `{sealed, nonce}`
// */
// export const encrypt = (message, senderSecretKey, recipientPublicKey, nonce, asHex = true) => {
// const result = naclSeal(
// strToU8a(message),
// hexToBytes(senderSecretKey),
// hexToBytes(recipientPublicKey),
// !!nonce
// ? hexToBytes(nonce)
// : newNonce(false),
// )
// return !asHex ? result : {
// sealed: bytesToHex(result.sealed),
// nonce: bytesToHex(result.nonce)
// }
// }
// export const mapDecrypt = (map, senderPublicKey, recipientSecretKey, keys) => isMap(map)
// && new Map(
// Array
// .from(map)
// .map(([key, value]) => {
// value = !isObj(value)
// ? value
// : decryptObj(value, senderPublicKey, recipientSecretKey, keys)
// return [key, value]
// })
// )
// export const mapEncrypt = (map, secretKey, recipientPublicKey, keys, asHex = true) => isMap(map)
// && new Map(
// Array
// .from(map)
// .map(([key, value]) => {
// value = !isObj(value)
// ? value
// : encryptObj(
// value,
// secretKey,
// recipientPublicKey,
// keys,
// asHex
// )[0]
// return [key, value]
// })
// )
// /**
// * @name encryptObj
// * @summary recursively encrypt specified or all properties of an object.
// *
// * @param {Object} result object to encrypt
// * @param {String|Uint8Array} secretKey
// * @param {String|Uint8Array} recipientPublicKey (optional) if not supplied, will encrypt using SecretBox.
// * Otherwise, will use Box encryption.
// * @param {Array} keys (optional) to encrypt only specified object properties.
// * If valid array, unlisted properties will not be encrypted.
// * If not a valid array, will attempt to encrypt all properties.
// * See examples for different usage cases.
// * @param {Boolean} asHex (optional) Default: true
// *
// * @returns {Object} ```javascript
// * [
// * result, // encrypted object.
// * isBox, // indicates whether encrypted using SecretBox or Box
// * ]
// * ```
// *
// * @example ```javascript
// * // object to encrypt
// * const obj = {
// * first: 'some text',
// * second: 1, // will be converted to string: '1'
// * third: 'ignored property',
// * fifth: null, // will be converted to string: 'null'
// * }
// *
// * // secondary object for recursive encryption
// * obj.fourth = {
// * a: [1, 2, 3], // will be converted to string
// * b: new Map([[1,1], [2,3]]), // will be converted to 2D Array and then to string
// * c: 'not to be encrypted', // will not be touched
// * }
// *
// * // specify which properties to encrypt. If `keys` is falsy, will encrypt everything.
// * const keys = [
// * 'first',
// * 'second',
// * 'fifth',
// * 'fourth',
// * // removing the below two items will encrypt the entire `fourth` object
// * 'fourth.a',
// * 'fourth.b',
// * ]
// *
// * // generate random sender's encryption keypair
// * const keyPair = encryptionKeypair(randomBytes(117))
// *
// * // generate random recipient's encryption keypair
// * const keyPairRecipient = encryptionKeypair(randomBytes(117))
// *
// * // encrypt using Box encryption
// * const [ box ] = encryptObj(
// * obj,
// * keyPair.secretKey,
// * keyPairRecipient.publicKey,
// * keys,
// * )
// *
// * // now attempt to decrypt the encrypted `box` object
// * const boxDecrypted = decryptObj(
// * box,
// * keyPairRecipient.publicKey,
// * keyPair.secretKey,
// * keys,
// * )
// *
// *
// * // encrypt using SecretBox/Secretkey encryption
// * const [ secretBox ] = encryptObj(
// * obj,
// * keyPair.secretKey,
// * null,
// * keys,
// * )
// *
// * // now attempt to decrypt the encrypted `box` object
// * const secretBoxDecrypted = decryptObj(
// * secretBox,
// * null,
// * keyPair.secretKey,
// * keys,
// * )
// *
// * // if sealed is null encryption has failed
// * console.log({
// * box,
// * boxDecrypted,
// * secretBox,
// * secretBoxDecrypted,
// * })
// * ```
// */
// export const encryptObj = (obj, secretKey, recipientPublicKey, keys, asHex = true) => {
// if (!isObj(obj)) return
// const result = objCopy(obj, {}, [])
// const isBox = isHex(recipientPublicKey) || isUint8Arr(recipientPublicKey)
// const encryptFn = isBox
// ? encrypt
// : secretBoxEncrypt
// const validKeys = !isArr(keys)
// // encrypt all properties
// ? Object.keys(result)
// // encrypt only specified properties
// : keys.filter(k => result.hasOwnProperty(k))
// for (let i = 0; i < validKeys.length; i++) {
// const key = validKeys[i]
// const value = result[key]
// if (!obj.hasOwnProperty(key)) continue
// // value is an object => recursively encrypt
// if (isObj(value)) {
// const childKeyPrefix = `${key}.`
// const childKeys = validKeys
// .filter(k => k.startsWith(childKeyPrefix))
// // get rid of prefix
// .map(k => k.replace(new RegExp(childKeyPrefix), ''))
// result[key] = encryptObj(
// value,
// secretKey,
// recipientPublicKey,
// childKeys.length > 0
// ? childKeys // encrypt only specified child keys
// : null, // encrypt all child keys
// )[0]
// continue
// }
// const { encrypted, nonce, sealed } = encryptFn(
// value,
// secretKey,
// // only include recipient public key if not secretBox encrption
// ...[isBox && recipientPublicKey].filter(Boolean),
// newNonce(false), // generate new nonce
// false,
// )
// if (!encrypted && !sealed) {
// console.log('Encryption failed', { value })
// throw new Error('Encryption failed')
// }
// const bytes = new Uint8Array([...nonce, ...(encrypted || sealed)])
// result[key] = !asHex
// ? bytes
// : bytesToHex(bytes)
// }
// return [
// result,
// isBox,
// ]
// }
// /**
// * @name encryptionKeypair
// * @summary generate encryption keypair from oo7-substrate library's `keyData` or PolkadotJS's `encoded`
// *
// * @param {String} keyData hex string
// * @param {Boolean} asHex whether to convert to `publicKey` and `secretKey` to hex string or keep as Uint8Array
// *
// * @returns {Object} { publicKey, secretKey }
// */
// export const encryptionKeypair = (keyData, asHex = true) => {
// const bytes = keyDataFromEncoded(keyData)
// const pair = naclBoxKeypairFromSecret(blake2b(bytes, null, 32))
// return !asHex
// ? pair
// : {
// publicKey: bytesToHex(pair.publicKey),
// secretKey: bytesToHex(pair.secretKey),
// }
// }
// /**
// * @name keyDateFromEncoded
// * @summary converts PolkadotJS keyring's `encoded` hex string to oo7-substrate style `keyData`, if required
// *
// * @param {String|Uint8Array} encoded hex string or bytes array. (Encoded: 117 bytes, KeyData: 96 bytes)
// * @param {Boolean} asHex (optional) Default: false
// *
// * @returns Uint8Array/String
// */
// export const keyDataFromEncoded = (encoded, asHex = false) => {
// // convert to Uint8Array if required
// encoded = hexToBytes(encoded)
// // Convert PolkadotJS keyring's `encoded` to oo7-substrate `keyData`
// if (encoded.length > 96) {
// encoded = new Uint8Array([
// ...encoded.slice(16, 80),
// ...encoded.slice(85)
// ])
// }
// return !asHex
// ? encoded
// : bytesToHex(encoded)
// }
// /**
// * @name keyInfoFromKeyData
// * @summary generates keypair and Polkadot address from encoded or keyData.
// * @description FYI: the generated keypair is not an encryption or signing keypair.
// *
// * @param {String|Uint8Array} keyData
// * @param {Number} ss58Format (optional) use to generate address for any supported parachain identity.
// * Default: 0 (Polkadot)
// * @param {Boolean} asHex (optional) if true, will convert `publicKey` and `secretKey` to hex string.
// * Otherwise, will leave as Uint8Array.
// * Default: false
// *
// * @returns {Object} { address, publicKey, secretKey }
// */
// export const keyInfoFromKeyData = (keyData = '', ss58Format, asHex = false) => {
// let bytes = keyDataFromEncoded(keyData, false)
// const publicKey = bytes.slice(64, 96)
// const secretKey = bytes.slice(0, 64)
// return {
// address: ss58Encode(publicKey, ss58Format),
// publicKey: asHex
// ? bytesToHex(publicKey)
// : publicKey,
// secretKey: asHex
// ? bytesToHex(secretKey)
// : secretKey
// }
// }
// /**
// * @name newNonce
// * @summary generate a new random 24 bytes nonce
// *
// * @param {Boolean} (optional) Default: true
// *
// * @returns {Uint8Array|String}
// */
// export const newNonce = (asHex = true) => randomBytes(24, asHex)
// /**
// * @name newSignature
// * @summary generate a new signature using keypair and a message
// *
// * @param {String} message
// * @param {String} publicKey
// * @param {String} secretKey
// * @param {Boolean} asHex (optional) Default: true
// *
// * @returns {String|Uint8Array} String Hex if `asHex = true`, otherwise, Uint8Array
// */
// export const newSignature = (message, publicKey, secretKey, asHex = true) => {
// const signature = naclSign(
// message,
// {
// publicKey: hexToBytes(publicKey),
// secretKey: hexToBytes(secretKey),
// }
// )
// return !asHex ? signature : bytesToHex(signature)
// }
// /**
// * @name randomBytes
// * @summary generate random bytes for use as nonce or bytes for keypair generation
// *
// * @param {Number} length
// * @param {Boolean} asHex
// *
// * @returns {Uint8Array|String}
// *
// * @example
// * ```javascript
// * // generate random bytes to be used to generate encryption or signing keypair
// * const keyData = randomBytes(96, true) // equivalent to oo7-substrate's `keyData`
// * const encryptKP = encryptionKeypair(keyData, true)
// * console.log({ keyData, encryptKP })
// *
// * const encoded = randomBytes(117) // equivalent to PolkadotJS keyring's `encoded`
// * const signKP = signingKeyPair(encoded, true)
// * console.log({ encoded, signKP})
// * ```
// */
// export const randomBytes = (length, asHex = true) => {
// const bytes = randomAsU8a(length)
// return !asHex
// ? bytes
// : bytesToHex(bytes)
// }
// /**
// * @name naclDecrypt
// * @summary decrypt an message that was encrytped using TweetNaclJS SecretBox (AKA secret key) encryption
// *
// * @param {Sting|Uint8Array} encrypted encrypted message (hex string or Uint8Array)
// * @param {Sting|Uint8Array} nonce random nonce to decrypt the message (hex string or Uint8Array)
// * @param {Sting|Uint8Array} secret encryption secret (hex string or Uint8Array)
// * @param {Boolean} asString (optional) whether to return decrypted message as string or Uint8Array
// *
// * @returns {String|Uint8Array} decrypted message, null if decryption failed
// */
// export const secretBoxDecrypt = (encrypted, nonce, secret, asString = true) => {
// const decrypted = naclDecrypt1(
// hexToBytes(encrypted),
// hexToBytes(nonce),
// hexToBytes(secret),
// )
// return !decrypted || !asString
// ? decrypted
// : u8aToStr(decrypted)
// }
// /**
// * @name naclEncrypt
// * @summary encrypt a message using TweetNaclJS SecretBox (AKA secret key) encryption.
// * All strings in the params are expected to be valid hex.
// *
// * @param {String|Uint8Array} message message to encrypt
// * @param {String|Uint8Array} secret secret key
// * @param {String|Uint8Array} nonce (optional) if falsy, a new nonce will be generated
// * @param {Boolean} asHex (optional) whether to return encrypted message as bytes or hex string
// * Default: true
// *
// * @returns {Object} `{ encrypted, nonce }` | null if encryption fails
// */
// export const secretBoxEncrypt = (message, secret, nonce, asHex = true) => {
// nonce = nonce || newNonce(false) // generate new nonce
// const result = naclEncrypt1(
// strToU8a(message),
// hexToBytes(secret),
// hexToBytes(nonce),
// )
// if (!asHex || !result.encrypted) return result
// return {
// encrypted: bytesToHex(result.encrypted),
// nonce: bytesToHex(result.nonce),
// }
// }
// /**
// * @name secretBoxKeyFromPW
// * @summary generates a TweetNacl SecretBox compatible secret key (hex string) from supplied seed/password
// *
// * @param {String} password
// *
// * @returns {String} hex string
// */
// export const secretBoxKeyFromPW = password => generateHash(
// password,
// 'blake2',
// 256, // DO NOT CHANGE
// )
// /**
// * @name signingKeyPair
// * @summary generate TweetNacl signing keypair using `keyData` (oo7-substrate) or `encoded` (PolkadotJS) hex string.
// *
// * @param {String|Uint8Array} keyData
// * @param {Boolean} asHex (optional) Default: true
// *
// * @returns {Object} `{ publicKey, secretKey }`
// */
// export const signingKeyPair = (keyData, asHex = true) => {
// const bytes = keyDataFromEncoded(keyData)
// const pair = naclKeypairFromSeed(blake2b(bytes, null, 32))
// return !asHex
// ? pair
// : {
// publicKey: bytesToHex(pair.publicKey),
// secretKey: bytesToHex(pair.secretKey),
// }
// }
// /**
// * @name verifySignature
// * @summary verify if a signature is valid
// *
// * @param {String|Uint8Array} message
// * @param {String|Uint8Array} signature
// * @param {String|Uint8Array} publicKey
// *
// * @returns {Boolean}
// */
// export const verifySignature = naclVerify
// export default {
// decrypt,
// encrypt,
// encryptObj,
// encryptionKeypair,
// keyDataFromEncoded,
// keyInfoFromKeyData,
// newNonce,
// newSignature,
// randomBytes,
// secretBoxDecrypt,
// secretBoxEncrypt,
// signingKeyPair,
// verifySignature,
// }