PBKDF2.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package rnpbkdf2;
  2. import com.facebook.react.bridge.Promise;
  3. import com.facebook.react.bridge.ReactApplicationContext;
  4. import com.facebook.react.bridge.ReactContextBaseJavaModule;
  5. import com.facebook.react.bridge.ReactMethod;
  6. import org.spongycastle.crypto.digests.SHA512Digest;
  7. import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator;
  8. import org.spongycastle.crypto.params.KeyParameter;
  9. import java.nio.charset.StandardCharsets;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.security.spec.InvalidKeySpecException;
  12. public class PBKDF2 extends ReactContextBaseJavaModule {
  13. private static final Integer SHA512_DIGEST_LENGTH = 512;
  14. public PBKDF2(ReactApplicationContext reactContext) {
  15. super(reactContext);
  16. }
  17. public static String bytesToHex(byte[] bytes) {
  18. final char[] hexArray = "0123456789abcdef".toCharArray();
  19. char[] hexChars = new char[bytes.length * 2];
  20. for (int j = 0; j < bytes.length; j++) {
  21. int v = bytes[j] & 0xFF;
  22. hexChars[j * 2] = hexArray[v >>> 4];
  23. hexChars[j * 2 + 1] = hexArray[v & 0x0F];
  24. }
  25. return new String(hexChars);
  26. }
  27. private static String derivationKey(String pwd, String salt, Integer cost, Integer length)
  28. throws NoSuchAlgorithmException, InvalidKeySpecException {
  29. PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
  30. gen.init(pwd.getBytes(StandardCharsets.UTF_8), salt.getBytes(StandardCharsets.UTF_8), cost);
  31. byte[] key = ((KeyParameter) gen.generateDerivedParameters(length)).getKey();
  32. return bytesToHex(key);
  33. }
  34. @Override
  35. public String getName() {
  36. return "PBKDF2";
  37. }
  38. @ReactMethod
  39. public void derivationKey(String pwd, String salt, Integer iterations, Promise promise) {
  40. try {
  41. String strs = derivationKey(pwd, salt, iterations, SHA512_DIGEST_LENGTH);
  42. promise.resolve(strs);
  43. } catch (Exception e) {
  44. promise.reject("-1", e.getMessage());
  45. }
  46. }
  47. }