How to securely save the redux-persist-transform-encrypt key?

2.1k Views Asked by At

i am trying to persist and encrypt the redux store my react-native app.

i am trying to use redux-persist-transform-encrypt as per the documentation:

import { persistReducer } from 'redux-persist'
import createEncryptor from 'redux-persist-transform-encrypt'

const encryptor = createEncryptor({
  secretKey: 'my-super-secret-key'
})

const reducer = persistReducer(
  {
    transforms: [encryptor]
  },
  baseReducer
)

but the big deal is to find a secure way to store 'my-super-secret-key'. I've successfully got it from user input and saved it with react-native-keychain. Now the problem is that the function to get the key from the keychain is asynchronous and i would need to get the key before the store initialisation.

The result would look like this

import { persistReducer } from 'redux-persist'
import createEncryptor from 'redux-persist-transform-encrypt'

const encryptionKey = // get the key here from the keychain before initiating the store

const encryptor = createEncryptor({
  secretKey: encryptionKey
})

const reducer = persistReducer(
  {
    transforms: [encryptor]
  },
  baseReducer
)

Do someone have any workaround for me?

1

There are 1 best solutions below

0
On

I also spent some time how to resolve this. At first I found nice library to save generated secret key into keychain called react-native-sensitive-info. After that I was facing the problem that getting and setting generated secret key is asynchronous. Then I figured out that AsyncStorage is used as a storage in the config for persistReducer and there was the way - let's create a storage which uses react-native-sensitive-info. After a while, I stumbled upon a library that already exists and is implementing exactly the same logic. This is it -> redux-persist-sensitive-storage.

Just use it like this:

...
import createSensitiveStorage from 'redux-persist-sensitive-storage';

const appReducer = combineReducers(myReducers);

const persistConfig = {
  key: 'root',
  storage: createSensitiveStorage({
    keychainService: 'myKeychain',
    sharedPreferencesName: 'mySharedPrefs'
  })
}

const persistedReducer = persistReducer(persistConfig, appReducer);
const store = createStore(persistedReducer, applyMiddleware(thunkMiddleware));
const persistor = persistStore(store);
...

That's it!