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

What is Generative AI?

Generative AI refers to a category of advanced algorithms designed to produce original content across…

2 weeks ago

5 Generative AI Video Tools Everyone Should Know About

Generative AI Video Tools Everyone Should Know About Generative AI is revolutionizing video creation, making…

2 weeks ago

What Exactly Are LLMs (Large Language Models)?

Large Language Models (LLMs)  are a transformative advancement in artificial intelligence, capable of understanding, processing,…

2 weeks ago

How Would You Use a Virtual Clothing Mirror in 2025

In the ever-evolving landscape of retail, virtual clothing mirrors stand out as a key differentiator,…

2 weeks ago

Introducing LetsNurture’s Smart Mirror for Retail and Beauty Businesses

As technology evolves, businesses in the retail and beauty sectors face increased pressure to innovate…

3 weeks ago

The Integral Role of AI in Augmenting the Future of AR

The technological realm is continuously evolving, and as it stands, Augmented Reality (AR) and Artificial…

3 weeks ago