Skip to content

Commit

Permalink
Use built-in PBKDF2 implementation for browsers (status-im#295)
Browse files Browse the repository at this point in the history
* add pbkdf2 browser implementation

* use webcrypto in pbkdf2

* rename pbkdf2 file

* use pbkdf2

* add changeset

* revert rename

* remove browser field from package.json

* use `resolve.alias` for pbkdf2 if test

* use `mode` in vite.config.ts

Co-authored-by: Felicio Mununga <[email protected]>
  • Loading branch information
prichodko and felicio authored Jul 19, 2022
1 parent d726b82 commit e1c4f05
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 3 deletions.
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
33 changes: 33 additions & 0 deletions packages/status-js/src/crypto/pbkdf2.browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { pbkdf2 as pbkdf2Type } from 'ethereum-cryptography/pbkdf2'

type PBKDF2 = typeof pbkdf2Type

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

const derivedKey = await window.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.browser'

const AES_KEY_LENGTH = 32 // bytes

/**
Expand Down
20 changes: 18 additions & 2 deletions packages/status-js/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,26 @@ import { defineConfig } from 'vite'

import { dependencies } from './package.json'

import type { Alias } from 'vite'

const external = [
...Object.keys(dependencies || {}),
// ...Object.keys(peerDependencies || {}),
].map(name => new RegExp(`^${name}(/.*)?`))

export default defineConfig(({ mode }) => {
const alias: Alias[] = []

if (mode === 'test') {
alias.push({
/**
* Note: `happy-dom` nor `jsdom` have Crypto implemented (@see https://github.com/jsdom/jsdom/issues/1612)
*/
find: /^.*\/crypto\/pbkdf2.browser$/,
replacement: 'ethereum-cryptography/pbkdf2',
})
}

return {
build: {
target: 'es2020',
Expand All @@ -24,9 +38,11 @@ export default defineConfig(({ mode }) => {
external,
},
},

resolve: {
alias,
},
test: {
// environment: 'happy-dom',
environment: 'happy-dom',
},
}
})

0 comments on commit e1c4f05

Please sign in to comment.