Categories: Blog

Store sensitive data using KeyChain

There is always some sensitive data that our App holds for instance, Passwords, Touch Id, Certificates, Tokens or Biometric information. In general, React Native does not come bundled with any way of storing sensitive data. However, there are pre-existing solutions for Android and iOS platforms.

In Native platform like Android/iOS they provide something like this:

[ Android ] – Secure Shared Preferences:

Shared Preferences is the Android equivalent for a persistent key-value data store. Data in Shared Preferences is not encrypted by default, but Encrypted Shared Preferences wraps the Shared Preferences class for Android, and automatically encrypts keys and values.

[ iOS ] – Keychain Services:

Keychain Services allows you to securely store small chunks of sensitive info for the user. This is an ideal place to store certificates, tokens, passwords, and any other sensitive information that doesn’t belong in Async Storage.

In order to use iOS Keychain services or Android Secure Shared Preferences, you can either write a bridge yourself or use a library that wraps them for you and provides a unified API at your own risk. There is a library to consider:

=>  react-native-keychain 

Lets see how we can implement this feature in our React native app:


Installation:

Installation is quite simple with the react-native-keychain library.

Run the following command in your terminal:

yarn add react-native-keychain


OR

npm i react-native-keychain
Make sure to link your library:

react-native link react-native-keychain 

If you are developing iOS, Run pod install in ios/ directory to install iOS dependencies. Finally, rebuild the application.

To check whether it’s successfully linked or not you can go through the  MainApplication.java.

Now run the app using react-native run-android or react-native run-ios depending on your target device. All set for the coding 🙂 .

Using the library in practice for the login feature of our App:

In this example we will store, retrieve, and use credentials for re-login to an app.

Step 01 — Save credentials on first time login.

We can use the setGenericPassword function to store user credentials (username and password) in the Keychain. (Note: By default, strings can be stored using their function. When storing objects, it is recommended to use JSON.stringify).

 

import * as Keychain from 'react-native-keychain';

const LoginPage = props => {

  

  const username = LetsNurture;

  const password = 'LNs@1234';

  

  await Keychain.setGenericPassword(username, password);

}

Step 02 — Retrieve Credentials

Use the function getGenericPassword to get the saved user credentials from the Keychain. (Note: By default, the function returns String. So when retrieving objects, it is recommended to use JSON.parse).

import * as Keychain from 'react-native-keychain';

const LoginPage = props => {

  const checkUserStatus = async () => {

    try {

      const credentials = await Keychain.getGenericPassword();

      }

    } catch (error) {

      console.log('Keychain couldn\'t be accessed!', error);

    }

  }

 }

Step 03 — Using in a real-world

In the following code snippet, the first checkUserStatus() function will be called within the use effect hook during the component mount and set user credentials by retrieving them by the Keystore.

Then login() the function will be invoked to log in to the user using obtained credentials.

import React, { useState } from 'react';

import * as Keychain from 'react-native-keychain';

const LoginScreen = props => {

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const [preLogTest, setPreLogTest] = useState(false);

  useEffect(() => {

    checkUserStatus();

  }, []);

  useEffect(() => {

    if (preLogTest) {

      login();

    }

  }, [password, email])

  const checkUserStatus = async () => {

    try {

      const credentials = await Keychain.getGenericPassword();

      if (credentials) {

        setPreLogTest(true);

        setEmail(credentials.username);

        setPassword(credentials.password);

      } else {

      setLoading(false);

      }

    } catch (error) {

      console.log('Keychain couldn\'t be accessed!', error);

      setLoading(false);

    }

  }

  const login = async () => {

    try {

      const response = await fetch('yoururl' + 'signin', {

        method: 'POST',

        headers: {

          Accept: 'application/json',

          'Content-Type': 'application/json',

        },

        body: JSON.stringify({

          email,

          password,

        }),

      });

      const responseJson = await response.json();

      var message = responseJson.msg;

      if (responseJson.success === true) {

          await Keychain.setGenericPassword(email, password);

        }

      }

    } catch (error) {

      console.error(error);

    }

  };

 }

Step 04 — Remove credentials

The function resetGenericPassword can remove all Keychain credentials in a scenario where users are logging out from the app.

import * as Keychain from 'react-native-keychain';

const LoginScreen = props => {

  const removeCredentials = async () => {

    try {

      const credentials = await Keychain.resetGenericPassword();

      }

    } catch (error) {

      console.log('Keychain couldn\'t be accessed!', error);

    }

  }

 }

Conclusion

I believe using a react-native-keychain is the best option to store Sensitive data in React-Native mobile apps. As I can see, the main advantage is the usage of the existing iOS Keychain and Android shared preferences under the hood. I hope you find this insightful. Happy coding!  🙂

If you want to share your own ideas regarding “Store sensitive data using KeyChain”, you can directly contact our expert team of android / iOS / react-native developers.

Lets Nurture

Share
Published by
Lets Nurture

Recent Posts

7 Powerful Psychological Triggers to Skyrocket Your Website Engagement

In the digital age, understanding the hidden forces driving user behavior is essential. By strategically…

7 months ago

What is haptics? How can we implement in in AR based mobile App? What are Haptics Use cases?

What is haptics?   Haptics refers to the use of touch feedback technology to simulate…

9 months ago

The Benefits of Using Virtual Reality in Business

In today's fast-paced and technologically driven world, businesses are constantly seeking innovative ways to stay…

1 year ago

A Closer Look at New Jersey’s Thriving Incubator Ecosystem

The Garden State, more popularly known as New Jersey, is not only known for its…

1 year ago

Why You Need a Mobile App for Your Business

In today's digital age, mobile apps have become an indispensable tool for businesses across all…

1 year ago

How to Optimize Your Website for Better User Experience

In today's digital era, a seamless and enjoyable user experience is crucial for the success…

1 year ago