Giter Site home page Giter Site logo

amitaymolko / react-native-rsa-native Goto Github PK

View Code? Open in Web Editor NEW
232.0 7.0 112.0 36.3 MB

A native implementation of RSA key generation and encryption/decryption.

License: MIT License

Java 32.61% JavaScript 6.11% Objective-C 7.14% Ruby 3.93% Starlark 1.26% Swift 48.94%

react-native-rsa-native's Introduction

Looking for maintainers

This project needs new maintainers, PRs also welcome

react-native-rsa-native

A native implementation of RSA key generation and encryption/decryption, sign/verify. Keychain implementation Implementation is in PKCS1

Support

iOS 10+ android 4.1+ (API 16)

Status

Features: Generation, Encryption, Decryption, Sign, Verify, Keychain support

Getting started

$ yarn add react-native-rsa-native

or:

$ npm install react-native-rsa-native --save

Older React-Native versions

If you are using an older version of React Native and are having issues try using v1.1.14

Example Usage

These basic examples show a typical use case using both promise chains and async/await. See the full API documentation below for more detail on the methods available.

Encrypt a message

Encrypt a message and subsequently decrypt it, using the RSA class in a promise chain structure.

import { RSA } from 'react-native-rsa-native';

let message = "my secret message";

RSA.generateKeys(4096) // set key size
.then(keys => {
    console.log('4096 private:', keys.private); // the private key
    console.log('4096 public:', keys.public); // the public key
    RSA.encrypt(message, keys.public)
    .then(encodedMessage => {
        console.log(`the encoded message is ${encodedMessage}`);
        RSA.decrypt(encodedMessage, keys.private)
        .then(decryptedMessage => {
            console.log(`The original message was ${decryptedMessage}`);
        });
    });
});

Sign a message

Sign a message and subsequently verify it, using the RSAKeychain class in an async/await structure.

import { RSAKeychain } from 'react-native-rsa-native';

async main() {
    let keyTag = 'com.domain.mykey';
    let message = "message to be verified";

    let publicKey = await generateKeyPair(keyTag);
    // Share the generated public key with third parties as desired.

    let messageSignature = await RSAKeychain.sign(message, keyTag);

    if (await RSAKeychain.verify(messageSignature, message, keyTag)) {
        // The signature matches: trust this message.
    } else {
        // The signature does not match.
    }

    await RSAKeychain.deletePrivateKey(keyTag);
}

async generateKeyPair(keyTag : string) {
    let keys = await RSAKeychain.generate(keyTag);
    return keys.public;
}

Check out example App.js for a full example

Documentation

RSA Class

A class that performs RSA cryptographic primitives in a simple and straightforward manner. If you would prefer to use the underlying operating system's built-in security keychain, use the RSAKeychain Class instead.

generateKeys

static generateKeys(keySize : number) : Promise<KeyPair>

Generate a public/private key pair of the given key size.

generate

static generate() : Promise<KeyPair>

Equivalent to generateKeys(2048)

encrypt

static encrypt(message : string, publicKey : string) : Promise<string>

Encrypt a given message with the provided public key, so it is decryptable with the matching private key.

decrypt

static decrypt(encodedMessage : string, privateKey : string) : Promise<string>

Decrypt a given encrypted message using the private key.

sign

static sign(message: string, privateKey : string) : Promise<string>

Sign a given message with the private key, so that any user with the message, the returned signature, and the matching public key can verify it was signed under this key.

verify

static verify(signature : string, message : string, publicKey : string) : Promise<boolean>

Verify whether or not a provided signature was produced by signing the given message with the private key paired to the provided public key.

RSAKeychain Class

Support: android 4.3+ (API 18)

Like the RSA Class, but when its methods are called, instead of directly accessing the private key, the private key is stored in the underlying operating system's keychain (see documentation for iOS and for Android) using a tag which the app can use to access it. Methods then take this tag instead of the private key.

generateKeys

static generateKeys(keyTag : string, keySize : number) : Promise<PublicKey>

Generate a public/private key pair of the given key size, and store the private key in the operating system keychain.

generate

static generate(keyTag : string) : Promise<KeyPair>

Equivalent to generateKeys(keyTag, 2048)

encrypt

static encrypt(message : string, keyTag : string) : Promise<string>

Retrieve the public key associated with the key tag, and encrypt a given message with that key, so it is decryptable with the matching private key.

decrypt

static decrypt(encodedMessage : string, keyTag : string) : Promise<string>

Decrypt a given encrypted message using the private key associated with the given key tag.

sign

static sign(message: string, keyTag : string) : Promise<string>

Sign a given message with the private key associated with the given key tag, so that any user with the message, the returned signature, and the matching public key can verify it was signed under this key.

signWithAlgorithm

static sign(message: string, keyTag : string, algorithm?: 'SHA256withRSA' | 'SHA512withRSA') : Promise<string>

Sign a given message with the private key associated with the given key tag, so that any user with the message, the returned signature, and the matching public key can verify it was signed under this key. The user can use SHA256withRSA or SHA512withRSA algorithm for signing. SHA256withRSA algorithm is not backward compatible on android and the user needs to generate new keypair for this to work. (available from ^1.1.0). The default is SHA512withRSA and if one wishes to use SHA512withRSA for signing without new keypair, then use the above sign method.

verify

static verify(signature : string, message : string, keyTag : string) : Promise<boolean>

Verify whether or not a provided signature was produced by signing the given message with private key associated with the given key tag.

verifyWithAlgorithm

static verify(signature : string, message : string, keyTag : string, algorithm?: 'SHA256withRSA' | 'SHA512withRSA') : Promise<boolean>

Verify whether or not a provided signature was produced by signing the given message with private key associated with the given key tag.

deletePrivateKey

static deletePrivateKey(keyTag : string) : Promise<boolean>

Delete the private key from the operating system's keychain. Returns true if the key was removed successfully.

KeyPair Type

Note: The KeyPair type does not strictly exist. Documentation provided here for convenience of understanding the return types of other methods.

Property Description
private : string The RSA private key.
public : string The RSA public key.

PublicKey Type

Note: The PublicKey type does not strictly exist. Documentation provided here for convenience of understanding the return types of other methods.

Property Description
public : string The RSA public key.

Credit

Donate

ETH: 0xDc2F8D78098749EB3ECdF79Fe32Efda86fEEFc3c

react-native-rsa-native's People

Contributors

ahahn avatar alexanderpinkerton avatar amitaymolko avatar aouaki avatar co-kevin avatar crafterm avatar dkvtieu avatar earonesty avatar jimcullenaus avatar johku90 avatar kokeksibir avatar lfalcao avatar maxisme avatar notatestuser avatar roaringunicorn avatar roris avatar saeedkargosha avatar saeedzhiany avatar soumyamishra89 avatar swissmanu avatar tommeier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-rsa-native's Issues

manual installation

I'd like to try this library out with our app, but we're not using cocoapods. Are there notes anywhere on how to manually link things up? Any other dependencies I need to also link?

Thanks!

null is not an object (Evaluating RSA.generateKeys)

Do you have an example in Java where you decrypt the message you encrypted with the code below? The key is in PKCS1 format and I can't seem to work this out in Java.

import { RSA } from 'react-native-rsa-native';

let message = "my secret message";
 
RSA.generateKeys(4096) // set key size
.then(keys => {
    console.log('4096 private:', keys.private); // the private key
    console.log('4096 public:', keys.public); // the public key
    RSA.encrypt(message, keys.public)
    .then(encodedMessage => {
        console.log(`the encoded message is ${encodedMessage}`);
        RSA.decrypt(encodedMessage, keys.private)
        .then(decryptedMessage => {
            console.log(`The original message was ${decryptedMessage}`);
        });
    });
});

Error in documentation

Hello,

Maybe I'm missing something but I think there is an error in the documentation

return RSAKeychain.encrypt(secret, keyTag) //should be RSAKeychain.encrypt(secret, keys.public)
      .then(encodedMessage => {
        console.log(encodedMessage);

        RSAKeychain.decrypt(encodedMessage, keyTag)
          .then(message => {
            console.log(message);
          })
        }) ```

Export Compliance

I'm just wondering if anyone has published an app on the App Store using this library.

For export compliance (https://help.apple.com/app-store-connect/#/devc3f64248f), one of the points says that if "Your app uses encryption limited to that within the Apple operating system" will not require further documentation.

Does this library fall under that category?

Undefined using Expo

Hi, I have an application running with Expo and I can't import RSA. Here is what I have:

import { RSA } from 'react-native-rsa-native'
console.log('RSA', RSA)

My log says it is undefined. Any idea why? Was it supposed to work with Expo? Thanks!

Key accessibility

Hi

Is it possible to restrict the accessibility settings using this library? I want to generate keys in the device keychain, and require the user to re-authenticate via either their device passcode or biometrics before being able to use them.

If not, are there any plans to support it in future?

These are the settings I'm referring to:

iOS: https://developer.apple.com/documentation/security/secaccesscontrolcreateflags
Android: https://developer.android.com/training/articles/keystore.html#UserAuthentication

Many thanks

Crash on iOS 9.3

After add this library, my app will crash on launch.
This happened only on iOS 9.3. Neither android nor iOS above 10.

Log in console:

dyld: Symbol not found: _kSecKeyAlgorithmRSAEncryptionPKCS1
Referenced from: ~/Library/Developer/CoreSimulator/Devices/8E4D3D08-FDD6-4A40-BA83-83BB05990B95/data/Containers/Bundle/Application/AFF781A8-19C7-465A-8716-6B0778B4D8E7/<MyApp>.app/<MyApp>
  Expected in: /Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 9.3.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security
 in ~/Library/Developer/CoreSimulator/Devices/8E4D3D08-FDD6-4A40-BA83-83BB05990B95/data/Containers/Bundle/Application/AFF781A8-19C7-465A-8716-6B0778B4D8E7/<MyApp>.app/<MyApp>

Using node-rsa to encrypt, not able to decrpyt in react native

Hi there,

I am using this library to generate key pair and then passing the public key to node server. There using node-rsa and encrypting the message, but when I am decrypting it back in react native, I am getting a blank string.

Do I have to specify the padding or format or something in node-rsa?

Android API 23 raising a "Only RSAKeyGenParameterSpec supported" error

Hi @amitaymolko

Hope all is going well mate.

Noticed in our testing with the Pixel emulator, API 23, that RSA land is throwing an error when generating keypairs mentioning that only RSAKeyGenParameterSpec is supported:

screen_shot_2017-07-19_at_12 12 31_pm_720

With a Nexus 5X simulator (API 24) all good, so looks like only an 23 issue perhaps?

Looking at the generate method that accepts a key tag for keystore identification, the KeyPairGenerator is given a KeyPairGenParameter rather than a RSAKeyGenParameterSpec. I had a bit of look at using RSAKeyGenParameterSpec rather than KeyPairGenParameter/builder, but the former doens't appear to have any keystore integration...

Any thoughts mate what might be going on in API 23 land?

Cheers,

Marcus

Pod Install issue

I am getting this when I attempt to run a pod install. Any idea why or what I can do to get this sorted out?

Thanks!

[!] CocoaPods could not find compatible versions for pod "react-native-rsa-native":
In Podfile:
react-native-rsa-native (from ../node_modules/react-native-rsa-native)

Specs satisfying the react-native-rsa-native (from ../node_modules/react-native-rsa-native) dependency were found, but they required a higher minimum deployment target.

Error on call RSA.generate()

When call RSA.generate(), an error occurs:
default

react-native: 0.50.3
ios emulator version: 11.2

import {
  Text,
  View,
} from 'react-native';
import { RSA, RSAKeychain } from 'react-native-rsa-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.generatekeys();
  }

  generatekeys = () => {
    RSA.generate()
      .then(keys => {
        console.log(keys.private) // the private key
        console.log(keys.public) // the public key
        RSA.encrypt('1234', keys.public)
          .then(encodedMessage => {
            RSA.decrypt(encodedMessage, keys.private)
              .then(message => {
                console.log(message);
              })
          })

        RSA.sign(secret, keys.private)
          .then(signature => {
            console.log(signature);

            RSA.verify(signature, secret, keys.public)
              .then(valid => {
                console.log(valid);
              })
          })
      });
  };

  render() {
    return (
      <View>
        <Text>
          Test
        </Text>
      </View>
    );
  }
}

pod file for react-native 6

Hi,

I have upgraded to react-native 6 and would like to use this package. However, I don't know how to install this without cocoapods. Will you guys be adding a pod file to the dist?

Thanks

Cannot read property 'generateKeys' of undefined

Hi,

I am trying to implement RSA in react native ver 0.55.4 on IOS 11.4, I am getting the error as:

TypeError: Cannot read property 'generateKeys' of undefined
TypeError: Cannot read property 'encrypt' of undefined

I am not able to resolve this issue as I have saved the react-native-rsa-native via npm and imported
RSA, RSAKeychain?

Doesn't build on Android

After adding react-native-rsa-native to our react-native project it couldn't build anymore.

react-native run-android fails with the following error:

> Task :react-native-rsa-native:compileDebugJavaWithJavac
Note: /Users/dusan-mitipi/Desktop/mvpmitipiapp/node_modules/react-native-rsa-native/android/src/main/java/com/RNRSA/RSA.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 15s
289 actionable tasks: 33 executed, 256 up-to-date
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html

cd android && ./gradlew installDebug --stacktrace gives the following stacktrace:

> Task :app:generateBundledResourcesHashDebug
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:60)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:128)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:311)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:202)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:132)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:45)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:71)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
        at com.android.builder.dexing.DxDexArchiveMerger.mergeMonoDex(DxDexArchiveMerger.java:177)
        at com.android.builder.dexing.DxDexArchiveMerger.mergeDexArchives(DxDexArchiveMerger.java:118)
        at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:97)
        at com.android.build.gradle.internal.transforms.ExternalLibsMergerTransform.transform(ExternalLibsMergerTransform.kt:121)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        ... 101 more
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
        at com.android.builder.dexing.DxDexArchiveMerger.lambda$mergeMonoDex$0(DxDexArchiveMerger.java:171)
Caused by: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Caused by: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:72)
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
Caused by: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
        at com.android.dx.merge.DexMerger$8.updateIndex(DexMerger.java:565)
        at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:276)
        at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:574)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:166)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
        ... 1 more


* Get more help at https://help.gradle.org

BUILD FAILED in 15s
245 actionable tasks: 8 executed, 237 up-to-date

It builds using Android Studio though.

Any help is appreciated, thanks.

DexIndexOverflowException while building on android

After I installed and linked this library I started getting the following issue on Gradle

Running dex in-process requires build tools 23.0.2.
For faster builds update this project to use the latest build tools.
Dex: Error converting bytecode to dex:
Cause: com.android.dex.DexIndexOverflowException: Cannot merge new index 68701 into a non-jumbo instruction!
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexIndexOverflowException: Cannot merge new index 68701 into a non-jumbo instruction!
        at com.android.dx.merge.InstructionTransformer.jumboCheck(InstructionTransformer.java:109)
        at com.android.dx.merge.InstructionTransformer.access$800(InstructionTransformer.java:26)
        at com.android.dx.merge.InstructionTransformer$StringVisitor.visit(InstructionTransformer.java:72)
        at com.android.dx.io.CodeReader.callVisit(CodeReader.java:114)
        at com.android.dx.io.CodeReader.visitAll(CodeReader.java:89)
        at com.android.dx.merge.InstructionTransformer.transform(InstructionTransformer.java:49)
        at com.android.dx.merge.DexMerger.transformCode(DexMerger.java:842)
        at com.android.dx.merge.DexMerger.transformMethods(DexMerger.java:813)
        at com.android.dx.merge.DexMerger.transformClassData(DexMerger.java:786)
        at com.android.dx.merge.DexMerger.transformClassDef(DexMerger.java:682)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:542)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
        at com.android.dx.command.dexer.Main.run(Main.java:277)
        at com.android.dx.command.dexer.Main.main(Main.java:245)
        at com.android.dx.command.Main.main(Main.java:106)

I uninstalled/unlinked the library and the exception went away.

I tried to use this library in two different and completely unrelated projects, and in both cases I got the same problem.

去掉头部/尾部 无法加解密了

1,当我使用
key = key.replace(/\n/g,'');
key = key.replace('-----BEGIN RSA PUBLIC KEY-----','');
key = key.replace('-----END RSA PUBLIC KEY-----','');
把密钥的头部和尾部去掉。这样会导致无法加解密
2,后台返回了不带头部/尾部公钥。无法进行加密

How to generate SHA256 key

How do i generate SHA256 key ? Appreciated your work,but if want to generate SHA256 then ?

IS there any method for that>?

Not running on Android, while using RSA.encrypt(msg,publicKey) method.

Getting error as:

Error: Attempt to invoke virtual method 'byte[] org.spongycastle.asn1.x509.SubjectPublicKeyInfo.getEncoded()' on a null object reference
at createErrorFromErrorData (NativeModules.js:152)
at NativeModules.js:104
at MessageQueue.__invokeCallback (MessageQueue.js:442)
at MessageQueue.js:127
at MessageQueue.__guard (MessageQueue.js:343)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:126)
at debuggerWorker.js:80

While using RSA.enrypt(msg, publicKey) method.

My code:

const publicKey = keys.public; (I'm receiving from an API as RSA string response)
RSA.encrypt(paramText, publicKey)
.then(encodedMessage => {
> console.log(the encoded message is ${encodedMessage});
}

Please reply soon.
Thank you.

Binary format?

Hi, thanks for the work.

Is there a way to get the encrypted message in binary?
(Uint8Array, regular array with Number values.. something like that?)

Thanks,
D.D.

import RSA alway null

I use sameple code

import { RSA } from 'react-native-rsa-native';
 
let message = "my secret message";
 
RSA.generateKeys(4096) // set key size
.then(keys => {
    console.log('4096 private:', keys.private); // the private key
    console.log('4096 public:', keys.public); // the public key
    RSA.encrypt(message, keys.public)
    .then(encodedMessage => {
        console.log(`the encoded message is ${encodedMessage}`);
        RSA.decrypt(encodedMessage, keys.private)
        .then(decryptedMessage => {
            console.log(`The original message was ${decryptedMessage}`);
        });
    });
});

but RSA alway null

Crash on iOS – attempt to insert nil object from objects[0]

Hello,

I'm seeing a bunch of crashes on iOS (11.2.5 and 11.2.6 so far) when generating a key using key chain :

Fatal Exception: RCTFatalException: Exception '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]' was thrown while invoking generate on target RNRSAKeychain with params (
    MY_KEY_TAG,
    344,
    345
)

My guess is that it's because of this code but I'm not sure :

- (NSString *)encodedPublicKey {
    if (self.keyTag) {
        __block NSString *encodedPublicKey = nil;

        [self performWithPublicKeyTag:self.keyTag block:^(SecKeyRef publicKey) {
            encodedPublicKey = [self externalRepresentationForPublicKey:publicKey];
        }];

        return encodedPublicKey;
    }

    return [self externalRepresentationForPublicKey:self.publicKeyRef];
}

The encodedPublicKey is only set inside a block and I guess it's called asynchronously (not an Objective-C expert unfortunately) and thus the encodedPublicKey can be returned nil. Maybe it's something else I'm not sure...

I'd love to make a PR fixing this if you can help me identify the problem!

Decrypting crash in ios

I made a small program that will crash in ios instantly:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { RSA } from 'react-native-rsa-native';

export default class App extends Component<{}> {
  render() {
    console.log("Starting");
    // This line will succeed
    //const encryptedMessage = 'oDPvLJ254KRxmim1Oe03mJY7Uhbl9zWSH9beynkDFhItfD3JqwfIG0u4hRoFLwLv2VpB2qlu7Ah5ZrRQaBTapmF9+dkPHPGpnF2Ze6bKdLmyc8+1iXXt8ZIM/Nrl3w/Kcb0IWPBn4AEIBycy0oeBlDYVIl6NnA3nspoVCHaXdP+fi4G7Mp4xyFTYSK+RcTe9IgLx6ZX4/IxykLymaUgdRJu09ZlJ5ubJ0l8KC+af+9NUMwoYdIM4hUckA+hOOtSO2DFkxmeFzwrX1rR97H08h3OoIX32m9Id0KJP7aoq9tBnAhnTnbkifgz2uD1aqm4IJeUS2hL07HDSZXEsXdsKJQ==';
    // This line will crash
    const encryptedMessage = 'aoDPvLJ254KRxmim1Oe03mJY7Uhbl9zWSH9beynkDFhItfD3JqwfIG0u4hRoFLwLv2VpB2qlu7Ah5ZrRQaBTapmF9+dkPHPGpnF2Ze6bKdLmyc8+1iXXt8ZIM/Nrl3w/Kcb0IWPBn4AEIBycy0oeBlDYVIl6NnA3nspoVCHaXdP+fi4G7Mp4xyFTYSK+RcTe9IgLx6ZX4/IxykLymaUgdRJu09ZlJ5ubJ0l8KC+af+9NUMwoYdIM4hUckA+hOOtSO2DFkxmeFzwrX1rR97H08h3OoIX32m9Id0KJP7aoq9tBnAhnTnbkifgz2uD1aqm4IJeUS2hL07HDSZXEsXdsKJQ==';
    const privateKey = '-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEA8UETY2xfp+Qf2S/9nOZ959CI6SthNWnWD2D9KBH38fV+mTrXTItu9PETbBjfbGKU89xIlNCPg7JNuwiAUNxnK5KgCfInqe9Ttz4aoEAqzRAgdqCxmg+OQNJQBDxG8ynmO1TZ80CDKKH54GRhNo7/ymLsOyHkIU7180Ht7XdM1fx2prMWW4OMNH9Y0KzR5lTBpUINpjODkAYIJWOXbZ0xZUlNSGSWiN8M5ZmO3lnUn72uQ3lpTGXnkLGv+6vQcY+ER5yyEq+Mr0Ghx/Scx9EoNarT6rReoGd6FpH6RTWq2U0uOs5S0XHR0W6vYpeDDEhTyceDxj1yRV1/1vVzleYrbQIDAQABAoIBAAGMJa1jv4hkDdX55f5yz+YhyYcHN4D41mI6ZxEHOyTPIiPqVqvtlfaC+ox6/H7SLdskk6zfWoeBW3I21vqHZlGcmMnc4GcezoBtF9opWvAgYx8NifLkulEG24S7+D6ItgikhnRtnLz1N2qHSCrhhVT39wBoGOC9Jlo/dPqIp3a/gFKV8JoNfYRq2iz8Wq+orWlAqBEyG8KNuAiqhee4HFUGL4HV2SbfgEcpQvNnpbkJ+1+4iu5sd1FLTS3hBcHcovyXqek57gEIj9kflO92lABQIsM4aNGzIEwOyF1du+423+900tpqy12W26YfGQRR+6f0kyqaVnJZbxqxSuz2Y7ECgYEA/drkCrhlhXwG0nWelpqhMhQKx7AUgfizKojKYi5LsqlutdtQt3oM5lE0lNDOkIplPJSOBuDaCy3aoeGs0P7EEPPgAY+duomRRp0spmLC5pSx4qTLRQ31KmLRoDLU9P738DaWFImOxf9t84RmbPDBPlHUHEvntRU3X0rcr7/16vUCgYEA80rtpREv8ux06mkGG8hSyjca0kL9o967EmZx2BDsfi9O2W2XixCdmq0ybFH+7/MEB6fyUMJuR4MA6LioZbpgE28Hok7qQi8BxPAOWLMEzE072E+R6KTkRqiEg8xyJl13UMZZyv55b+hwpLK4zq6eoCxv7gnABMCnfCoCoI/QY5kCgYEAxVBqiFqjromk09lQl0dBnCcv6d7XUd75hEom5QGPHSPNRdVee/6GIE9mS3Wx2W95GQlvC7GiSaYulj1PknMz+ulUaGI0+1UKcpSgrAN/8rIJQl1NEjOzKGr+/UIFfRjhpvkG1pfFPek4kVuMMYlA6yu3bvcg9wOysoMB3imbADECgYAkvopJxeDCBahaxuXfSFAIrm3kl62LFFaYntRO16+AF1EHUZ/zptzGwaW96lxgjQlsxpa4T8UsE8MNYuY8Bvv/s2MpxlVnDYZs4fyotNDisj95mfrlchHwAf+RkE0lMjSVBIAHQovAtRBeL4ft3z2h31RAVUSk8xvYite+vDmy8QKBgD3IIxh60ZOaj16Kb6KwWeDcmz0E/u6BvBoomRY1JvP4HiIrzSO/TnFOX+BR20M219mxY3vLpCZFv11B1rRi19dmywVLS3nVyObpnmMyfIHKuYCfzmpwYtPG08khOMo4KVO5i8QIXYdu/5Xc1MGUWuNSyK5/1vB7gwBFj0TpE3dA-----END RSA PRIVATE KEY-----';
    RSA.decrypt(encryptedMessage, privateKey).then(() => {
      console.log("SUCCESS");
    });     
    return (
      <View>
        <Text>hi</Text>
      </View>
    ); 
  }   
}     

The private key there was generated just for this example. The top encrypted message was made with the paired public key, and then I just added an 'a' to the front of it to cause a crash.

The crash I get is:

Thread 7 Crashed:: Dispatch queue: com.apple.root.default-qos
0   CoreData                            0x00007fff23aa6bb5 CFDataGetLength + 5
1   com.apple.Security                  0x00007fff2bb583bd SecRSAPrivateKeyCopyOperationResult + 280
2   com.apple.Security                  0x00007fff2bb386c7 SecKeyRunAlgorithmAndCopyResult + 216
3   com.apple.Security                  0x00007fff2bb3be96 __SecKeyRSACopyDecryptedWithPadding_block_invoke + 35
4   com.apple.Security                  0x00007fff2bb3c04c PerformWithBigEndianToCCUnit + 165
5   com.apple.Security                  0x00007fff2bb3be30 SecKeyRSACopyDecryptedWithPadding + 272
6   com.apple.Security                  0x00007fff2bb389ef SecKeyRunAlgorithmAndCopyResult + 1024
7   com.apple.Security                  0x00007fff2bb38f86 SecKeyCreateDecryptedDataWithParameters + 113
8   org.reactjs.native.example.PAuth    0x0000000101b1ea21 __22-[RSANative _decrypt:]_block_invoke + 113
9   org.reactjs.native.example.PAuth    0x0000000101b1e8fe -[RSANative _decrypt:] + 542 (RSANative.m:210)
10  org.reactjs.native.example.PAuth    0x0000000101b1e658 -[RSANative decrypt:] + 120 (RSANative.m:182)
11  org.reactjs.native.example.PAuth    0x0000000101b18562 __42-[RNRSA decrypt:withKey:resolve:rejecter:]_block_invoke + 130 (RNRSA.m:59)
12  libdispatch.dylib                   0x00007fff516ac810 _dispatch_call_block_and_release + 12
13  libdispatch.dylib                   0x00007fff516ad781 _dispatch_client_callout + 8
14  libdispatch.dylib                   0x00007fff516af829 _dispatch_queue_override_invoke + 834
15  libdispatch.dylib                   0x00007fff516bcbfc _dispatch_root_queue_drain + 350
16  libdispatch.dylib                   0x00007fff516bd39e _dispatch_worker_thread2 + 99
17  libsystem_pthread.dylib             0x00007fff518cd6b3 _pthread_wqthread + 583
18  libsystem_pthread.dylib             0x00007fff518cd3fd start_wqthread + 13

Looking at the ios code in RSANative.m doesn't yield any obvious fruit, but I wanted to expand to more eyeballs. It looks like (after a little testing) that most any garbage string put into decrypt will crash the whole app.

Does not work with Android

Hi,

I get an error saying "Keychain error: TypeError: Cannot read property 'encrypt' of undefined" when I try the code in android. Works fine in iOS.

TypeError: null is not an object (evaluating '_reactNativeRsaNative.RSA.generateKeys')

When using this in my react-native project I'm getting the following:

[Unhandled promise rejection: TypeError: null is not an object (evaluating '_reactNativeRsaNative.RSA.generateKeys')]
* screens/auth/SignInScreen.tsx:21:12 in signInAsync$
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:271:30 in invoke
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:135:28 in invoke
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:170:17 in <unknown>
- node_modules/promise/setimmediate/core.js:45:7 in tryCallTwo
- node_modules/promise/setimmediate/core.js:200:23 in doResolve
- node_modules/promise/setimmediate/core.js:66:12 in Promise
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:169:27 in callInvokeWithMethodAndArg
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:192:38 in enqueue
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:216:8 in async
* screens/auth/SignInScreen.tsx:12:24 in signInAsync
- node_modules/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.android.js:213:45 in touchableHandlePress
- node_modules/react-native/Libraries/Components/Touchable/Touchable.js:878:34 in _performSideEffectsForTransition
- ... 21 more stack frames from framework internals

Code:

RSA.encrypt("[email protected]", rsaPublic)
    .then(encodedMessage => {
        console.log(encodedMessage);
    })

rsaPublic:

const rsaPublic = `-----BEGIN PUBLIC KEY-----
sdasdAasdasdasdasdsadsadas...Bs6aEf6hjjkmfgHISntpAgMB
AAE=
-----END PUBLIC KEY——`;

org.spongycastle.util.io.pem.PemObject.getContent()' on a null object reference (JCERSAPublicKey)

On Android when i code

RSA.verify(signature, secret, `
    -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx9Van+tCkoPDTs/U8KAl
k5LDUZ7f643MPz50lKT1CJbhosefAFrI7CP+joy61ROCx2JYeRo6BrA98oanPm5m
0fcqLDV8gpT/LYSbsafU9e7t8mkTd052QimI8UmZGbhcg5L2cbOE9PSNFSqGR+vN
FFgRYYMBu4uN3HCSrW8N6ObqlQCz57EGrpRbfAdqLKjXxtXOhL4UxV06geUUFzjf
QU0Iko6xshRJvCV4+SIF9MRPTXnUsMWcNCsRKGQXx6dMQEsh/PV6cXIoIdVuPqZg
CWXOeyTIZI/Hmpv+7OkaBtDREa3rvDFXOE17pjXRXd1QIUQfcpytlP8scLIFrO8M
2wIDAQAB
-----END PUBLIC KEY-----
    `)
      .then(valid => {
        console.log(valid);
      })
      .catch(err => {
        console.log(err)
      })

Throws error:

org.spongycastle.util.io.pem.PemObject.getContent()' on a null object reference
    at createErrorFromErrorData (NativeModules.js:115)
    at NativeModules.js:78
    at MessageQueue.__invokeCallback (MessageQueue.js:296)
    at MessageQueue.js:120
    at MessageQueue.__guard (MessageQueue.js:218)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:119)
    at debuggerWorker.js:71

How encrypt from publickey string

Here is my code
let pub = '30820122300D06092A864886F70D01010105000382010F003082010A0282010100AE14891B84B9D0799BA0ED4BC3F1A1789EE9D895DF10E2E2FCD0129D1671C094D4A69EA30893F8798A5C1DF9E4F7A43F19E00812819C48B1BF75432770A08D5A6C47F9C4889C16AC128CE1CCF5E8C51BB46371867D1C22B0C1E3BF364F35305D5648BC99890441D5EFC2904128F8646742BD35E031040EA528F972F31C5F6D774FF4049ECFE9120DAEA96F60EAE20ABD662B56CB18FD04259BE63F907BA3C1EF93E773EA54D6E80773331055DCC007E79A9FD2FCEEE165CE5E8D6BB574BD65A09B2AA18A6A07A884355126B3C054AE6B6183C486F7C64E896421CAFDA30566A9F7FD264C383903BB1BB9C3ABE656EC92513210C87D61F285419144AEDC9E4F730203010001'
let message = "my secret message";
let ecrpyt = await RSA.encrypt(message, pub);
I'm can't use this to encrypt.
Is there any way to encrypt it?
Please help !!!

How can I translate Node-RSA code to this library?

  // Internal: Get the device's public key. This is used to encrypt the
  // Wifi password when configuring a network, because the HTTP request goes
  // over an open network in the clear!
  static getPublicKey = async () => {
    const { b: rawDerPublicKey, r: responseCode } = await fetchJSON(
      `${AP_URL}/public-key`,
    );

    if (responseCode !== 0) {
      throw new Error('Error getting public key');
    }

    const derBuffer = Buffer.from(rawDerPublicKey, 'hex');

    const publicKey = new NodeRSA(derBuffer.slice(22), 'pkcs1-public-der', {
      encryptionScheme: 'pkcs1',
    });
    publicKey.importKey(derBuffer.slice(22), 'pkcs1-public-der');

    return publicKey;
  }

}

I need to translate this node rsa code to this library, but I can't figure it out how to do it. I'll really appreciate any help,

Warning Module RNRSA requires main queue setup since it overrides `constantsToExport` but doesn't implement `requiresMainQueueSetup`.

I get this warning message when launching the app
I can ignore it but I felt you should be aware

WARN     Module RNRSA requires main queue setup since it overrides `constantsToExport` but doesn't implement `requiresMainQueueSetup`. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.

WARN     Module RNRSAKeychain requires main queue setup since it overrides `constantsToExport` but doesn't implement `requiresMainQueueSetup`. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.

CocoaPods could not find compatible versions for pod "react-native-rsa-native"

It is not the first time that I am having this error! I don't know what to do, it's the only project that has this error.

When running pod install, the terminal returns the following message:

[!] CocoaPods could not find compatible versions for pod "react-native-rsa-native":
  In Podfile:
    react-native-rsa-native (from `../node_modules/react-native-rsa-native`)

Specs satisfying the `react-native-rsa-native (from `../node_modules/react-native-rsa-native`)` dependency were found, but they required a higher minimum deployment target.

Generated Public is not vaild with opensll

Version: Android
I generated a Key Pair.
If i use the Public Key and copy to a file.
for Example:

-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAop0q4PS1hfvGB07eMwXdHIKd+WAYbed6G6rus8zsRFRyBBS+TN0d\nI4hDfFeI4W0dZaP4GURqw3Ulc1TPepFN8XDU6CcuFbKuyBjMZNGuVWNl67xdLz0F\nJNZboZlvBaHkubEI7j3cXhXaENwyh4ljiZuFm5M71euke0jRpGJNs77mbWVvvlXY\nhMRxVzQFnfsf/rtzMmgtbdTR2qsMJOtCorKSkmdh06v61TGs5HYoY80AXlIedC8t\nIMBYPAwhHbaiu62m69llt+1aIxjIqy2EH4opevjTDPeDNTWDMrkoE++OPIetWokH\n6bdrWQZcEuVTUg26gf9Ns8Pgt6y9AE5FAQIDAQAB\n-----END RSA PUBLIC KEY-----\n

And check with openssl
(I remove the String RSA
openssl rsa -noout -text -inform PEM -in pubKeyFile.pem -pubin
i get this error:

unable to load Public Key
140585687942808:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1197:
140585687942808:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:374:Type=X509_ALGOR
140585687942808:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:697:Field=algor, Type=X509_PUBKEY
140585687942808:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c

What i do wrong.
Why it is not Valid ?
Thank you for help

Cannot read property 'verify' of undefined in Jest

My impletement:
import { RSAKeychain } from 'react-native-rsa-native';
RSAKeychain.verify(signatureString, data, rsaPublicKey);

Error I got in Jest unit test:
TypeError: Cannot read property 'verify' of undefined

Does anyone know how to solve this?

Or it is not possible to run in Jest as all the code sit in Android and iOS?

Encryption using .pem file which contains public key same as SwiftyRSA library

Hi amitaymolko,

Thanks for your library.

I need to apply encryption on user password using .pem file which contains public key.
It should be working like SwiftyRSA library written for Swift coding language.

Could you please suggest me how to achieve this kind of encryption using your library in ReactNative which should work for both platforms (iOS/Android)?

Thanks in advance

Best reagrds
Kirtish Jain

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.