Coder Social home page Coder Social logo

craftzdog / react-native-aes-gcm-crypto Goto Github PK

View Code? Open in Web Editor NEW
243.0 4.0 28.0 1.49 MB

AES-GCM encryption/decryption for React Native

License: MIT License

Kotlin 13.87% JavaScript 10.34% Java 26.74% TypeScript 13.54% C 0.44% Objective-C 16.73% Swift 14.51% Ruby 3.84%
react-native cryptography

react-native-aes-gcm-crypto's Introduction

react-native-aes-gcm-crypto

AES-GCM encryption/decryption for React Native

Requirements

  • iOS >= 13.0
  • Android >= 26

Installation

npm install react-native-aes-gcm-crypto

Usage

import AesGcmCrypto from 'react-native-aes-gcm-crypto';

const key = 'Yzg1MDhmNDYzZjRlMWExOGJkNTk5MmVmNzFkOGQyNzk=';

AesGcmCrypto.decrypt(
  'LzpSalRKfL47H5rUhqvA',
  key,
  '131348c0987c7eece60fc0bc',
  '5baa85ff3e7eda3204744ec74b71d523',
  false
).then((decryptedData) => {
  console.log(decryptedData);
});

AesGcmCrypto.encrypt('{"name":"Hoge"}', false, key).then((result) => {
  console.log(result);
});

Encrypt data

type EncryptedData = {
  iv: string;
  tag: string;
  content: string;
};

function encrypt(
  plainText: string,
  inBinary: boolean,
  key: string
): Promise<EncryptedData>;
  • plainText: A string data to encrypt. If inBinary is true, it should be encoded in Base64.
  • inBinary: true to encrypt binary data encoded with Base64
  • key: AES key in Base64

Encrypt file

function encryptFile(
  inputFilePath: string,
  outputFilePath: string,
  key: string
): Promise<{
  iv: string;
  tag: string;
}>;
  • inputFilePath: A file path to encrypt
  • outputFilePath: An output file path
  • key: AES key in Base64

Decrypt data

function decrypt(
  base64Ciphertext: string,
  key: string,
  iv: string,
  tag: string,
  isBinary: boolean
): Promise<string>;
  • base64Ciphertext: A base64 data to decrypt.
  • key: AES key in Base64
  • iv: An initialization vector (or nonce) in Hex
  • tag: An auth tag in Hex
  • isBinary: true to return decrypted data in Base64

Decrypt file

function decrypt(
  inputFilePath: string,
  outputFilePath: string,
  key: string,
  iv: string,
  tag: string
): Promise<boolean>;
  • inputFilePath: A file path to decrypt
  • outputFilePath: An output file path
  • key: AES key in Base64
  • iv: An initialization vector (or nonce) in Hex
  • tag: An auth tag in Hex
  • isBinary: true to return decrypted data in Base64

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

Author

Takuya Matsuyama | @inkdrop_app

Made for my app called Inkdrop - A Markdown note-taking app

License

MIT

react-native-aes-gcm-crypto's People

Contributors

craftzdog avatar sandipndev 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

react-native-aes-gcm-crypto's Issues

erorr unexpected token

Error: Unexpected error
at Object.promiseMethodWrapper [as encrypt] (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:105:51)
at handleNext (C:\Users\LENOVO\Documents\edc-neropay\src\screens\listToken\ListToken.js:53:18)
at Pressability._performTransitionSideEffects (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Pressability\Pressability.js:756:11)
at Pressability._receiveSignal (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Pressability\Pressability.js:693:12)
at onResponderRelease (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Pressability\Pressability.js:524:14)
at Object.invokeGuardedCallbackProd (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:107:10)
at invokeGuardedCallback (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:340:31)
at invokeGuardedCallbackAndCatchFirstError (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:364:25)
at executeDispatch (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:466:3)
at executeDispatchesInOrder (C:\Users\LENOVO\Documents\edc-neropay\node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:490:5)

with my code 

    const data = {
 
  transactionId,
  text: 'mumbai',
  dynamic: true,
};
const secretKey = Api.SECRET_KEY;
const stringEncrypt = JSON.stringify(data)


AesGcmCrypto.encrypt(stringEncrypt, true, secretKey).then((result) => {
  console.log(result);
}).catch((error) => {
  console.error("Kesalahan Enkripsi:", error);
});

Why does the Android SDK need to be at least 26?

Thank you for providing this great library!

I have a question. Why does the Android SDK need to be at least 26 to use this? That means we cannot support android 7 and below. If you have a reason, could you please tell me?

Expo

Will it work with Expo? Thanks!

Android failing Encrypt with "Unexpected Error"

It works fine on iOS

const key = Buffer.from(
        crypto.getRandomValues(new Uint8Array(32)),
      ).toString('base64');

const {iv, tag} = await AesGcmCrypto.encryptFile(file, uri, key);
Unexpected error
    at Object.promiseMethodWrapper [as encryptFile]

Error when using EncryptFile or DecryptFile in Expo project

Hi,

There was no template issue, so hopefully, this will be a format that will provide the right information.

First and foremost, thank you for the work on this library. It's working great for encrypting plain text content in our application.

We are now looking to extend the encryption to files, but we are running into a few issues with encryptFile (and subsequently decryptFile)

I hope to get some guidance on how to tackle this.

Context

I am getting:

  • Unexpected error on Android which I believe comes from this line
  • IOError: Could not open file for reading on iOS which I believe comes from this line

When attempting to do:

import RNAesGcmCrypto from 'react-native-aes-gcm-crypto';
import * as Crypto from 'expo-crypto';
import * as FileSystem from 'expo-file-system';

// setup the target folder in which the encrypted file should be put
const encryptedFileFolderPath = `${FileSystem.documentDirectory}temporary-downloads`;
await FileSystem.makeDirectoryAsync(encryptedFileFolderPath, { intermediates: true });
const encryptedFilePath = `${encryptedFileFolderPath}/${Crypto.randomUUID()}.jpeg`;

// filepath contains a file returned by the camera roll using https://docs.expo.dev/versions/latest/sdk/imagepicker/
const fileStats = (await FileSystem.getInfoAsync(filePath, { size: true })) as FileSystem.FileInfo & { size: number };
console.log(` info JSON.stringify(fileStats) ${JSON.stringify(fileStats)}`); // confirms that the file exists

const encryptFileResult = await RNAesGcmCrypto.encryptFile(filePath, encryptedFilePath, encryptionKey);

Questions

  1. Is there any specific requirements for the library to be able to access the files from the expo FileSystem?

(my thoughts) Expo specifies that the files are restricted to the app, I believe the library should have the same context, so I wonder if it's a permission issue.

  1. Is the file encryption done in chunks or is the entire file read in memory?

(my thoughts) I was looking at using FileSystem.readAsStringAsync which allows to read chunks of the file and provide the chunks to the encryption function as a workaround.

I would love to get thoughts or quick comments on the questions and the errors. Thanks in advance for the time!

Info

I am using:

  • Expo: 48.0.18
  • Expo-file-system: ~15.2.2
  • react-native-aes-gcm-crypto: ^0.2.2

I was testing on:

  • iPhone 14, running iOs 16.6
  • Android phone running Android 9

I use the Expo dev client. I am not sure if you are familiar, but it's the client that you build using EAS build

Not working with 32 bit AES key

Not working with 32 bit AES key
Here is my code. i am generating 32 bit AES key.

//Key generation
export function GenerateRandom256BitAESKey() {
    return crypto.randomBytes(32).toString('hex');

}

//encryption code
export function encryptWithGcm(_toEncrypt ,key) {
    const _key = GenerateRandom256BitAESKey() 
    AesGcmCrypto.encrypt('{"name":"Hoge"}', false, _key).then((result) => {
        console.log({result});
      });
}

Getting below error

Possible Unhandled Promise Rejection (id: 0):
│ Error: Failed to encrypt
│ Error: Failed to encrypt

Its working fine if change key size to 16.
Any help would be appreciated, Thank you

Support fort AES-CBC

Hi,

I am successfully using this module but now I am faced with supporting AES-CBC; openSSL insists at encrypting my private RSA key with CBC.

I did try a few react native module that supposed to support CBC but without success. And they take a string as input (one actually does it for the key too!!!), which would not work with a binary data or totally random keys (which I need to support).

Is it possible to add CBC support,. despite the name of this project? How anyone has a suggestion for a good AES-CBC module?

[TypeError: null is not an object (evaluating '_reactNativeAesGcmCrypto.default.decrypt')]

i got this error when run line:

const key = rsaKeyRef.current
            const iv = rsaKeyRef.current.slice(0, 16)
            const decrypt = AesGcmCrypto.decrypt(data, key, iv, '', true)
            .then(result => {
                console.log('decrypt result', result)
            }).catch(error => {
                console.log('decrypt error', error)
            })
            

the pod is install success
Installing react-native-aes-gcm-crypto (0.2.1)
can u help?

Not able to Install pod

I m getting following error when trying to install pod, although dependencies already been addded.
[!] The following Swift pods cannot yet be integrated as static libraries:

The Swift pod react-native-aes-gcm-crypto depends upon React-Core, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set use_modular_headers! globally in your Podfile, or specify :modular_headers => true for particular dependencies.

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.