0
当我尝试在keyStore中加载(KeyStore方法)以前保存的数据时,我收到EOFException
。创建文件并保存数据(从KeyStore存储方法)。我想知道我应该在代码中更改以从文件中获取数据。 保存(创建一个文件,创建入口等):未从文件初始化的KeyStore
@Override
public boolean savePIN(Context context, int pin) throws StorageAlreadyInitializedException {
boolean containKey;
OutputStream outputStream = null;
if (mKeyStore == null) {
initializeKeyStore(context);
}
if (mKeyStore != null) {
try {
containKey = mKeyStore.containsAlias(PASSWORD_ALLIAS);
//if key is in keystore then throw exception
if (containKey) {
throw new StorageAlreadyInitializedException();
}
SecretKey secretKey = KeyGenerator.getInstance(ALGORITHM_TYPE).generateKey();
KeyStore.PasswordProtection password = new KeyStore.PasswordProtection((pin + "").toCharArray());
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
Log.v(TAG, "Secret key" + secretKey.toString() + " Secret Key encoded " + secretKey.getEncoded().toString());
mKeyStore.setEntry(PASSWORD_ALLIAS, secretKeyEntry, password);
// mKeyStore.setKeyEntry(PASSWORD_ALLIAS,pinByte,null);
File file = new File(context.getFilesDir().getAbsolutePath(), KEYSTORE_NAME);
if (!file.exists()) {
file.createNewFile();
}
outputStream = new FileOutputStream(file);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
// FileOutputStream
mKeyStore.store(bOut, (pin + "").toCharArray());
if (bOut != null) {
outputStream.write(bOut.toByteArray());
}
// Log.v(TAG, "savePin " + (pin + "").toCharArray());
Key key = mKeyStore.getKey(PASSWORD_ALLIAS, (pin + "").toCharArray());
Log.v(TAG, "output stream: " + outputStream.toString());
Log.v(TAG, "Created key: " + key.getEncoded().toString());
} catch (... e) {
More exceptions...
加载:
private void initializeKeyStore(Context context, int pin) {
InputStream inputStream = null;
try {
mKeyStore = KeyStore.getInstance("BKS");
File file = new File(context.getFilesDir().getAbsolutePath(), KEYSTORE_NAME);
if (!file.exists()) {
file.createNewFile();
}
inputStream = new FileInputStream(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
mKeyStore.load(inputStream, (pin + "").toCharArray());
}catch(...exceptions){}