Skip to content

Commit

Permalink
feat: run crypto_pwhash on separate thread
Browse files Browse the repository at this point in the history
  • Loading branch information
lyubo committed Oct 26, 2020
1 parent 7803f72 commit 99e7c42
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
4 changes: 4 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ android {
targetSdkVersion 28
versionCode 1
versionName "0.1"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
externalNativeBuild {
cmake {
arguments "-DANDROID_TOOLCHAIN=clang"
Expand Down
37 changes: 24 additions & 13 deletions android/src/main/java/org/libsodium/rn/RCTSodiumModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.util.Base64;
import android.util.Log;

Expand All @@ -21,6 +24,12 @@

public class RCTSodiumModule extends ReactContextBaseJavaModule {

private static final ExecutorService executor = Executors.newSingleThreadExecutor();

private void runOnExecutor(Runnable runnable) {
executor.execute(runnable);
}

static final String ESODIUM = "ESODIUM";
static final String ERR_BAD_KEY = "BAD_KEY";
static final String ERR_BAD_MAC = "BAD_MAC";
Expand Down Expand Up @@ -402,20 +411,22 @@ else if (skb.length != Sodium.crypto_box_secretkeybytes())

@ReactMethod
public void crypto_pwhash(final Integer keylen, final String password, final String salt, final Integer opslimit, final Integer memlimit, final Integer algo , final Promise p) {
try {
byte[] saltb = Base64.decode(salt, Base64.NO_WRAP);
byte[] passwordb = Base64.decode(password, Base64.NO_WRAP);
byte[] out = new byte[keylen];
runOnExecutor(() -> {
try {
byte[] saltb = Base64.decode(salt, Base64.NO_WRAP);
byte[] passwordb = Base64.decode(password, Base64.NO_WRAP);
byte[] out = new byte[keylen];

int result = Sodium.crypto_pwhash(out, out.length, passwordb, passwordb.length, saltb, opslimit, memlimit, algo);
if (result != 0)
p.reject(ESODIUM,ERR_FAILURE);
else
p.resolve(Base64.encodeToString(out, Base64.NO_WRAP));
}
catch (Throwable t) {
p.reject(ESODIUM,ERR_FAILURE,t);
}
int result = Sodium.crypto_pwhash(out, out.length, passwordb, passwordb.length, saltb, opslimit, memlimit, algo);
if (result != 0)
p.reject(ESODIUM,ERR_FAILURE);
else
p.resolve(Base64.encodeToString(out, Base64.NO_WRAP));
}
catch (Throwable t) {
p.reject(ESODIUM,ERR_FAILURE,t);
}
});
}

@ReactMethod
Expand Down

0 comments on commit 99e7c42

Please sign in to comment.