7

I have multiple key, value and I dont know how can I store multiple key, value in different places.

Is there an alternative way for the following code using react-native-keychain package ??

await AsyncStorage.setItem('pincode',  '12345');
await AsyncStorage.setItem('userid',  '@user8383928');
await AsyncStorage.setItem('contacts',  JSON.stringify(contacts_array_of_object));

Every above key, value saving may called in different functions and in a different time.

Problem is in react-native-keychain there is only two property username, password:

async () => {
  const username = 'zuck';
  const password = 'poniesRgr8';

  // Store the credentials
  await Keychain.setGenericPassword(username, password);

  try {
    // Retrieve the credentials
    const credentials = await Keychain.getGenericPassword();
    if (credentials) {
      console.log('Credentials successfully loaded for user ' + credentials.username);
    } else {
      console.log('No credentials stored');
    }
  } catch (error) {
    console.log('Keychain couldn\'t be accessed!', error);
  }
  await Keychain.resetGenericPassword();
}
Pasquale
  • 389
  • 3
  • 11
Muhammad
  • 2,572
  • 4
  • 24
  • 46
  • Does anyone know the solution for this? https://stackoverflow.com/questions/75081431/get-the-value-of-a-specified-field-from-a-keychain-with-multiple-key-value-pairs Thanks! – Teodora Jan 11 '23 at 10:20

2 Answers2

9

1) setInternetCredentials

setInternetCredentials(server, username, password) accepts server as first parameter. Server can be any string.

await setInternetCredentials('pincode', 'pincode', '123456');
await setInternetCredentials('contacts', 'contacts', JSON.stringify(contacts_array_of_object));

You can then get it from keychain using

await getInternetCredentials('pincode');

2) setGenericPassword with service value

setGenericPassword(username, password, [{ accessControl, accessible, accessGroup, service, securityLevel }]) You have to specify service value, which is the name used for storing secret in internal storage

await setGenericPassword('pincode', '123456', [{ service = 'pincode' }]);

3) JSON.strigify with setGenericPassword

Every time you would want to write something you would read keystore first and use object spread to store it back together with a new value.

Black
  • 9,541
  • 3
  • 54
  • 54
  • In the latest version `Options` type for `setGenericPassword` is an object, so invocation would be `await setGenericPassword('pincode', '123456', { service: 'pincode' });` – Sergiy Ostrovsky Apr 05 '23 at 10:51
3

put them all in one object and then save it as JSON.stringify({...})

Muhammad
  • 2,572
  • 4
  • 24
  • 46
Belqis
  • 79
  • 1
  • 9