tectiv3 / react-native-aes

Native module for AES encryption
MIT License
188 stars 135 forks source link

How encrypt and decrypt strings in Web Apps #51

Closed adcastiblanco closed 3 years ago

adcastiblanco commented 3 years ago

I am using React Native Aes as follows and working:

export const encryptData = (text) => {
  return Aes.encrypt(text, KEY_ENCRYPT, null).then((cipher) => cipher);
};

export const decryptData = (encryptedData) =>
  Aes.decrypt(encryptedData, KEY_ENCRYPT, null);

and my backend service with ruby ​​can encrypt and decrypt with a similar method.

Now, I want to use the same backend service for my Web App with React JS and use the same encryption on Web

But, when I try it with Crypto JS Aes it doesn't work, or I still don't know how to use it on the web.

I have a code with CryptoJS and an encrypted message generated with React Native Aes. I use the same secret key but it returns an error or an empty object:

    // Decrypt

    var bytes = CryptoJS.AES.decrypt(messageEncryptedWithReactNative, secretKeyUsedReactNative);
    var originalText = bytes.toString(CryptoJS.enc.Utf8);

    console.log("DECRYPTED", originalText); // this it returns null

Is there a way to encrypt and decrypt the data generated in React Native and use it in React JS with Crypto JS?

matthiaszyx commented 3 years ago

@adcastiblanco I have the same problem. Did you figure out how to use CryptoJS in a way that is compatible with this libray?

Edit: I had a look at the native code for this library and came up with a CryptoJS equivalent: const decrypted = CryptoJS.AES.decrypt(text, CryptoJS.enc.Hex.parse(key), { iv: CryptoJS.enc.Hex.parse(iv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }).toString(CryptoJS.enc.Utf8);

const encrypted = CryptoJS.AES.encrypt(text, CryptoJS.enc.Hex.parse(key), { iv: CryptoJS.enc.Hex.parse(iv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }).toString();

bondanherumurti commented 3 years ago

@adcastiblanco can you share the ruby implementation on decrypt the text

adcastiblanco commented 3 years ago

Thanks for your help, finally I solved it as follow:

var key = CryptoJS.enc.Hex.parse(process.env.REACT_APP_KEY_ENCRYPT); var iv = CryptoJS.enc.Hex.parse("");

export const ENCRYPT_DATA = (data) => CryptoJS.AES.encrypt(data, key, { iv: iv }).toString();

export const DECRYPT_DATA = (data) => CryptoJS.AES.decrypt(data, key, { iv: iv,}).toString(CryptoJS.enc.Utf8);