Practice and reinforce the concepts from Lesson 6
Implement client-side encryption for sensitive user data in a mental health support app, ensuring data privacy even from app developers.
Your peer support app stores:
Install Encryption Library:
npm install react-native-keychain @react-native-async-storage/async-storage crypto-js
Generate User-Specific Key:
import CryptoJS from 'crypto-js';
import { Keychain } from 'react-native-keychain';
const generateUserKey = async (userId) => {
const existingKey = await Keychain.getInternetCredentials(userId);
if (existingKey) {
return existingKey.password;
}
const newKey = CryptoJS.lib.WordArray.random(256/8).toString();
await Keychain.setInternetCredentials(userId, userId, newKey);
return newKey;
};
Encrypt Sensitive Data:
const encryptData = (data, userKey) => {
const jsonString = JSON.stringify(data);
const encrypted = CryptoJS.AES.encrypt(jsonString, userKey).toString();
return encrypted;
};
const decryptData = (encryptedData, userKey) => {
const decrypted = CryptoJS.AES.decrypt(encryptedData, userKey);
const jsonString = decrypted.toString(CryptoJS.enc.Utf8);
return JSON.parse(jsonString);
};
Storage with Encryption:
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeSecureData = async (key, data, userKey) => {
try {
const encryptedData = encryptData(data, userKey);
await AsyncStorage.setItem(key, encryptedData);
} catch (error) {
console.error('Storage error:', error);
}
};
const retrieveSecureData = async (key, userKey) => {
try {
const encryptedData = await AsyncStorage.getItem(key);
if (encryptedData) {
return decryptData(encryptedData, userKey);
}
return null;
} catch (error) {
console.error('Retrieval error:', error);
return null;
}
};
Saving Crisis Notes:
const saveCrisisNote = async (noteContent, userId) => {
const userKey = await generateUserKey(userId);
const noteData = {
content: noteContent,
timestamp: new Date().toISOString(),
mood: currentMood
};
await storeSecureData(`crisis_note_${Date.now()}`, noteData, userKey);
};
const loadCrisisNotes = async (userId) => {
const userKey = await generateUserKey(userId);
const keys = await AsyncStorage.getAllKeys();
const crisisNoteKeys = keys.filter(key => key.startsWith('crisis_note_'));
const notes = await Promise.all(
crisisNoteKeys.map(async (key) => {
return await retrieveSecureData(key, userKey);
})
);
return notes.filter(note => note !== null);
};
This implementation ensures:
Complete this activity and submit your work through the Activity Submission Form