Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import React, { Component } from 'react';
import {
KeyboardAvoidingView,
Platform,
SegmentedControlIOS,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View,
} from 'react-native';
import * as Keychain from 'react-native-keychain';
const ACCESS_CONTROL_OPTIONS = ['None', 'Passcode', 'Password'];
const ACCESS_CONTROL_MAP = [null, Keychain.ACCESS_CONTROL.DEVICE_PASSCODE, Keychain.ACCESS_CONTROL.APPLICATION_PASSWORD, Keychain.ACCESS_CONTROL.BIOMETRY_CURRENT_SET]
export default class KeychainExample extends Component {
state = {
username: '',
password: '',
status: '',
biometryType: null,
accessControl: null,
};
componentDidMount() {
Keychain.getSupportedBiometryType().then(biometryType => {
this.setState({ biometryType });
});
}
export const setKeychainDataObject = (data: KeyChainData) => Keychain
.setGenericPassword(KEYCHAIN_DATA_KEY, JSON.stringify(data), {
accessControl: Platform.select({
ios: Keychain.ACCESS_CONTROL.BIOMETRY_ANY_OR_DEVICE_PASSCODE,
android: Keychain.ACCESS_CONTROL.BIOMETRY_ANY,
}),
accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED,
service: KEYCHAIN_SERVICE,
})
.catch(() => null);
const encryptedPassword = keychainObject.password;
const decrypted = await instance.decryptPassword(encryptedPassword);
keychainObject.password = decrypted.password;
instance.isAuthenticating = false;
return keychainObject;
}
instance.isAuthenticating = false;
}
return null;
},
async setGenericPassword(key, password, authOptions) {
const encryptedPassword = await instance.encryptPassword(password);
return Keychain.setGenericPassword(key, encryptedPassword, { ...defaultOptions, ...authOptions });
},
ACCESS_CONTROL: Keychain.ACCESS_CONTROL,
ACCESSIBLE: Keychain.ACCESSIBLE,
AUTHENTICATION_TYPE: Keychain.AUTHENTICATION_TYPE
};
export const setKeychainDataObject = (data: KeyChainData) => Keychain
.setGenericPassword(KEYCHAIN_DATA_KEY, JSON.stringify(data), {
accessControl: Platform.select({
ios: Keychain.ACCESS_CONTROL.BIOMETRY_ANY_OR_DEVICE_PASSCODE,
android: Keychain.ACCESS_CONTROL.BIOMETRY_ANY,
}),
accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED,
service: KEYCHAIN_SERVICE,
})
.catch(() => null);
static async encryptBySystemPin(dataKey: string, masterKey: string) {
if (Platform.OS === 'android') {
await KeyStoreBridge.initSystemPinKeys(dataKey)
const systemPinEncryptedMasterKey = await KeyStoreBridge.encryptData(
masterKey,
dataKey,
)
return systemPinEncryptedMasterKey
}
if (Platform.OS === 'ios') {
await Keychain.setGenericPassword('', masterKey, {
service: dataKey,
accessControl: Keychain.ACCESS_CONTROL.DEVICE_PASSCODE,
accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
})
return ''
}
throw new Error('Unsupported platform')
}