@@ -11,6 +11,7 @@ import { numToUint8Array, symmetricNonceSize } from "./Helpers";
1111import { Rollsum } from "./Chunker" ;
1212
1313import type rnsodiumType from "react-native-sodium" ;
14+ import { ProgrammingError } from "./Exceptions" ;
1415
1516const sodium = _sodium ;
1617
@@ -42,15 +43,37 @@ export function concatArrayBuffersArrays(buffers: Uint8Array[]): Uint8Array {
4243 return ret ;
4344}
4445
45- export async function deriveKey ( salt : Uint8Array , password : string ) : Promise < Uint8Array > {
46+ export enum KeyDerivationDifficulty {
47+ Hard = 90 ,
48+ Medium = 50 ,
49+ Easy = 10 ,
50+ }
51+
52+ export async function deriveKey ( salt : Uint8Array , password : string , difficulty = KeyDerivationDifficulty . Hard ) : Promise < Uint8Array > {
4653 salt = salt . subarray ( 0 , sodium . crypto_pwhash_SALTBYTES ) ;
54+ let opslimit : number ;
55+
56+ switch ( difficulty ) {
57+ case KeyDerivationDifficulty . Hard :
58+ opslimit = sodium . crypto_pwhash_OPSLIMIT_SENSITIVE ;
59+ break ;
60+ case KeyDerivationDifficulty . Medium :
61+ opslimit = sodium . crypto_pwhash_OPSLIMIT_MODERATE ;
62+ break ;
63+ case KeyDerivationDifficulty . Easy :
64+ opslimit = sodium . crypto_pwhash_OPSLIMIT_INTERACTIVE ;
65+ break ;
66+ default :
67+ throw new ProgrammingError ( "Passed invalid difficulty." ) ;
68+
69+ }
4770
4871 try {
4972 const ret = await Argon2 . hash ( {
5073 hashLen : 32 ,
5174 pass : password ,
5275 salt,
53- time : sodium . crypto_pwhash_OPSLIMIT_SENSITIVE ,
76+ time : opslimit ,
5477 mem : sodium . crypto_pwhash_MEMLIMIT_MODERATE / 1024 ,
5578 parallelism : 1 ,
5679 type : Argon2 . ArgonType . Argon2id ,
@@ -68,7 +91,7 @@ export async function deriveKey(salt: Uint8Array, password: string): Promise<Uin
6891 32 ,
6992 sodium . to_base64 ( sodium . from_string ( password ) , sodium . base64_variants . ORIGINAL ) ,
7093 sodium . to_base64 ( salt , sodium . base64_variants . ORIGINAL ) ,
71- sodium . crypto_pwhash_OPSLIMIT_SENSITIVE ,
94+ opslimit ,
7295 sodium . crypto_pwhash_MEMLIMIT_MODERATE ,
7396 sodium . crypto_pwhash_ALG_DEFAULT
7497 ) ;
@@ -79,7 +102,7 @@ export async function deriveKey(salt: Uint8Array, password: string): Promise<Uin
79102 32 ,
80103 sodium . from_string ( password ) ,
81104 salt ,
82- sodium . crypto_pwhash_OPSLIMIT_SENSITIVE ,
105+ opslimit ,
83106 sodium . crypto_pwhash_MEMLIMIT_MODERATE ,
84107 sodium . crypto_pwhash_ALG_DEFAULT
85108 ) ;
0 commit comments