amitaymolko / react-native-rsa-native

A native implementation of RSA key generation and encryption/decryption.
MIT License
232 stars 112 forks source link

This Lib works with Expo? #163

Open matheusbento opened 8 months ago

matheusbento commented 8 months ago

Hey guys.

I'm working with Expo, I tried to implement this library inside a react hooks, but when I try to run using this code:

import { createContext, useContext, useMemo, ReactNode } from "react";
import { RSA } from 'react-native-rsa-native';

export type CryptoContextType = {
  encrypt: any;
};

export const Crypto = createContext<CryptoContextType | null>(null);

const useCrypto = () => {
  const context = useContext(Crypto);
  if (!context) {
    throw new Error("useCrypto must be within CryptoProvider");
  }

  return context;
};

interface CryptoProviderProps {
  children: ReactNode;
}

const CryptoProvider = ({ children }: CryptoProviderProps) => {
  const encrypt = (text: string): Promise<string | boolean> => {
    // ...

    return new Promise(async (resolve, reject) => {
      try {

        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}`);
                });
            });
        });
        // resolve(encrypted);
      } catch (error) {
        console.log({ error });
        reject(error);
      }
    });
  };

  const providerValue = useMemo(
    () => ({
      encrypt,
    }),
    [encrypt]
  );

  return <Crypto.Provider value={providerValue}>{children}</Crypto.Provider>;
};

export { CryptoProvider, useCrypto };

I'm getting:

LOG {"error": [TypeError: Cannot read property 'generateKeys' of null]} WARN [TypeError: Cannot read property 'generateKeys' of null] LOG {"error": undefined} LOG {"error": [TypeError: Cannot read property 'generateKeys' of null]} WARN [TypeError: Cannot read property 'generateKeys' of null] LOG {"error": undefined} LOG {"error": [TypeError: Cannot read property 'generateKeys' of null]} WARN [TypeError: Cannot read property 'generateKeys' of null] LOG {"error": undefined}

Is needed any extra work to do on this?

ksetrin commented 8 months ago

@matheusbento No, React Native Modules don't work with Expo.

Rehankhalil462 commented 7 months ago

@ksetrin React Native Modules do work in Expo. Give a look at Expo Development Builds. @matheusbento