Я пишу приложение для Android, где я хочу сохранить некоторые файлы, которые зациклены. Когда я пытаюсь читать более крупные строки, которые были написаны, записаны в файлы, я получаю следующее исключение при их расшифровке:
Invalid argument (internal Keystore code: -38 message: In KeystoreOperation::finish
У кого -нибудь есть идея, почему это не работает или что я делаю не так?public byte[] read() throws MyReadException {
byte[] data;
try {
FileInputStream input = new FileInputStream(this.file_path);
int iv_size = input.read();
byte[] iv = new byte[iv_size];
input.read(iv);
int encrypted_byte_size = input.read();
byte[] data_encrypted = new byte[encrypted_byte_size];
input.read(data_encrypted);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, this.getKey(), new IvParameterSpec(iv));
data = cipher.doFinal(data_encrypted);
input.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException |
IllegalBlockSizeException | BadPaddingException | KeyStoreException |
InvalidAlgorithmParameterException | UnrecoverableEntryException |
CertificateException e) {
throw new MyReadException(e);
}
return data;
}
public void write(byte[] data) throws MyWriteException {
try {
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, this.getKey());
byte[] config_encrypted = cipher.doFinal(data);
FileOutputStream stream = new FileOutputStream(this.file_path);
stream.write(cipher.getIV().length);
stream.write(cipher.getIV());
stream.write(config_encrypted.length);
stream.write(config_encrypted);
stream.close();
} catch (BadPaddingException | NoSuchAlgorithmException | InvalidKeyException |
NoSuchPaddingException | KeyStoreException | InvalidAlgorithmParameterException |
UnrecoverableEntryException | IllegalBlockSizeException | CertificateException e) {
throw new MyWriteException(e);
}
}
private Key getKey() throws UnrecoverableEntryException, KeyStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, IOException {
KeyStore store = KeyStore.getInstance("AndroidKeyStore");
store.load(null);
Key key = store.getKey(key_alias, null);
if(key == null) {
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
generator.init(new KeyGenParameterSpec.Builder(
key_alias,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.setUserAuthenticationRequired(false)
.setRandomizedEncryptionRequired(true).build());
return generator.generateKey();
}
return key;
}
Подробнее здесь: https://stackoverflow.com/questions/771 ... erationfin