-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
90 lines (80 loc) · 2.36 KB
/
index.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
import { NativeModules } from 'react-native'
import { base16, base64 } from 'rfc4648'
const { RNFastCrypto } = NativeModules
const Buffer = require('buffer/').Buffer
async function pbkdf2DeriveAsync(
data: Uint8Array,
salt: Uint8Array,
iterations: number,
size: number,
alg: string
) {
if (alg !== 'sha512') {
throw new Error('ErrorUnsupportedPbkdf2Algorithm: ' + alg)
}
const out = await RNFastCrypto.pbkdf2Sha512(
base64.stringify(data),
base64.stringify(salt),
iterations,
size
)
return base64.parse(out, { out: Buffer.allocUnsafe })
}
export async function scrypt(passwd, salt, N, r, p, size) {
passwd = base64.stringify(passwd)
salt = base64.stringify(salt)
console.log(
'RNFS:scrypt(' + N.toString() + ', ' + r.toString() + ', ' + p.toString()
)
const t = Date.now()
const retval: string = await RNFastCrypto.scrypt(passwd, salt, N, r, p, size)
const elapsed = Date.now() - t
console.log('RNFS:script finished in ' + elapsed + 'ms')
let uint8array = base64.parse(retval)
return uint8array.subarray(0, size)
}
async function publicKeyCreate(privateKey: Uint8Array, compressed: boolean) {
const privateKeyHex = base16.stringify(privateKey)
const publicKeyHex: string = await RNFastCrypto.secp256k1EcPubkeyCreate(
privateKeyHex,
compressed
)
const outBuf = base16.parse(publicKeyHex, { out: Buffer.allocUnsafe })
return outBuf
}
async function privateKeyTweakAdd(privateKey: Uint8Array, tweak: Uint8Array) {
const privateKeyHex = base16.stringify(privateKey)
const tweakHex = base16.stringify(tweak)
const privateKeyTweakedHex: string =
await RNFastCrypto.secp256k1EcPrivkeyTweakAdd(privateKeyHex, tweakHex)
const outBuf = base16.parse(privateKeyTweakedHex, {
out: Buffer.allocUnsafe
})
return outBuf
}
async function publicKeyTweakAdd(
publicKey: Uint8Array,
tweak: Uint8Array,
compressed: boolean
) {
const publicKeyHex = base16.stringify(publicKey)
const tweakHex = base16.stringify(tweak)
const publickKeyTweakedHex: string =
await RNFastCrypto.secp256k1EcPubkeyTweakAdd(
publicKeyHex,
tweakHex,
compressed
)
const outBuf = base16.parse(publickKeyTweakedHex, {
out: Buffer.allocUnsafe
})
return outBuf
}
export const secp256k1 = {
publicKeyCreate,
privateKeyTweakAdd,
publicKeyTweakAdd
}
export const pbkdf2 = {
deriveAsync: pbkdf2DeriveAsync
}