Cross-Platform Encryption Libraries
Cross-Platform Encryption Libraries
Using well-tested encryption libraries ensures security and compatibility across platforms.
React Native Encryption Example:
// React Native - Cross-platform encryption
import CryptoJS from 'crypto-js';
import * as Keychain from 'react-native-keychain';
import AsyncStorage from '@react-native-async-storage/async-storage';
class SecureStorage {
async initialize() {
// Check if master key exists
const hasKey = await Keychain.hasInternetCredentials('AppMasterKey');
if (!hasKey) {
// Generate new master key
const masterKey = CryptoJS.lib.WordArray.random(256/8).toString();
await Keychain.setInternetCredentials(
'AppMasterKey',
'master',
masterKey,
{
accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
authenticatePrompt: 'Authenticate to access secure storage',
authenticationPromptBiometric: true
}
);
}
}
async encryptAndStore(key, value) {
try {
// Retrieve master key
const credentials = await Keychain.getInternetCredentials('AppMasterKey');
const masterKey = credentials.password;
// Encrypt value
const encrypted = CryptoJS.AES.encrypt(
JSON.stringify(value),
masterKey
).toString();
// Store encrypted data
await AsyncStorage.setItem(key, encrypted);
return true;
} catch (error) {
console.error('Encryption error:', error);
return false;
}
}
async retrieveAndDecrypt(key) {
try {
// Retrieve encrypted data
const encrypted = await AsyncStorage.getItem(key);
if (!encrypted) return null;
// Retrieve master key
const credentials = await Keychain.getInternetCredentials('AppMasterKey');
const masterKey = credentials.password;
// Decrypt value
const decrypted = CryptoJS.AES.decrypt(encrypted, masterKey);
const value = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
return value;
} catch (error) {
console.error('Decryption error:', error);
return null;
}
}
}