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

Best AI Web Design Tools In 2025 To Build Your Dream Website Faster

Web design was once an element of online brand-building that you needed to know how…

1 month ago

AI In Finance: How Machine Learning Is Transforming Banking

Financial services and banking are being reshaped and revolutionized by what artificial intelligence has made…

1 month ago

Can I Add Google Maps To My Android App: A Step-By-Step Integration Guide

Yes, you can add Google Maps to your Android app, providing seamless, interactive mapping for…

1 month ago

Future-Proof Your SEO: Top Digital Marketing Trends You Need To Leverage In 2025

SEO and digital marketing are constantly evolving. It happens slowly but quickly at the same…

1 month ago

The Ethics of AI: Balancing Innovation with Responsibility

As an AI development team, we regularly encounter scenarios and questions from clients regarding AI…

1 month ago

How AI-Powered Predictive Analytics Is Shaping Business Decisions

Predictive analytics is your ultimate guide to data-backed business strategy. Data-driven insights, proactive decision-making, and…

2 months ago