Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use built-in PBKDF2 implementation #295

Merged
merged 9 commits into from
Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/itchy-apes-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@status-im/js': patch
---

use built-in crypto for pbkdf2
3 changes: 3 additions & 0 deletions packages/status-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,8 @@
],
"publishConfig": {
"access": "public"
},
"browser": {
felicio marked this conversation as resolved.
Show resolved Hide resolved
"crypto": false
}
}
50 changes: 50 additions & 0 deletions packages/status-js/src/crypto/pbkdf2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import _crypto from 'crypto'

import type { pbkdf2 as pbkdf2Type } from 'ethereum-cryptography/pbkdf2'

type PBKDF2 = typeof pbkdf2Type

let crypto: Crypto

if (globalThis.crypto) {
crypto = globalThis.crypto
} else if (_crypto.webcrypto) {
/**
* Note: allows debugging and testing with `vite-node` and `vitest`
*
* Note: `webcrypto` is experimental (@see https://nodejs.org/dist/latest-v16.x/docs/api/webcrypto.html#web-crypto-api)
*/
crypto = _crypto.webcrypto as unknown as Crypto
} else {
throw new Error('Crypto is not supported in this environment')
}

export const pbkdf2: PBKDF2 = async (
password: Uint8Array,
salt: Uint8Array,
iterations: number,
keylen: number
): Promise<Uint8Array> => {
const cryptoKey = await crypto.subtle.importKey(
'raw',
password,
{ name: 'PBKDF2' },
false,
['deriveBits']
)

const derivedKey = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt,
iterations,
hash: {
name: 'SHA-256',
},
},
cryptoKey,
keylen << 3
)

return new Uint8Array(derivedKey)
}
3 changes: 2 additions & 1 deletion packages/status-js/src/utils/generate-key-from-password.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { pbkdf2 } from 'ethereum-cryptography/pbkdf2'
import { utf8ToBytes } from 'ethereum-cryptography/utils'

import { pbkdf2 } from '../crypto/pbkdf2'

const AES_KEY_LENGTH = 32 // bytes

/**
Expand Down