alpha0010 / react-native-file-access

Filesystem access for React Native
MIT License
298 stars 18 forks source link

writeFile doesn't work properly with ciphered data #82

Open MaksymKuzmych opened 3 months ago

MaksymKuzmych commented 3 months ago

react-native: 0.73.6 react-native-file-access: 3.0.7 Platform: Android

Bug I use node-forge to cipher my data. When I try to writeFile, it doesn't write all cipheredBytes. For example, there are 2 cases, when I try to readFile that was written by react-native-file-access (1 photo) and by react-native-fs (2 photo). Of course after that I can't properly decipher it when I want to see my image. Any ideas why it's happening?

Details

Screenshot 2024-04-01 at 15 41 39

photo_2024-04-01_15-57-38

alpha0010 commented 3 months ago

When reading/writing the data, are you using base64 encoding? If you have not specified, this library defaults to utf8, which likely truncates on the first null character in the binary data.

MaksymKuzmych commented 3 months ago

When reading/writing the data, are you using base64 encoding? If you have not specified, this library defaults to utf8, which likely truncates on the first null character in the binary data.

With react-native-fs I used 'utf8' (your lib works the same, if you don't pass any encoding, it'll be utf8). Any opportunity to not "truncates on the first null character in the binary data"? As I see it truncates after '§' symbol.

alpha0010 commented 3 months ago

It looks like node-forge's API supports outputting data in base 64, which this library should be able to handle fine (if you set the encoding parameter). Does that meet your needs?


The way React Native passes strings between JS and native code is unsafe for binary data (strings containing null characters). The workaround for this is to base 64 encode the data for the round trip. react-native-fs automatically encodes/decodes all strings passed through its API in base 64, which allows this to work for binary data (almost; it still processes as strings with js polyfilled atob/btoa implementations, which are not binary safe, but handles more cases than doing nothing, so if you have a small sample set, you are unlikely to notice problems).

In this library, I avoided the automatic internal conversions, since it is a performance cost that might not be need if the app is only working with text data. Instead, the app explicitly chooses when to pay the extra cost of base 64 encoding/decoding.