Я загружаю файл PDF, используя AsyncTask
в Android. В методе onPostExecute()
я написал код для его шифрования. Зашифрованный файл создается в хранилище, но не может быть успешно расшифрован.
Я проверил алгоритм шифрования и дешифрования, и он работает в обоих направлениях. Я использую CipherInputStream
и CipherOutputStream
для шифрования и дешифрования файлов.
Я уже пробовал шифровать файлы в потоке. Это все еще не работает.
public class EncryptionUtils {
private final static String ALGO_RANDOM_NUM_GENERATOR = "SHA1PRNG";
private final static String ALGO_SECRET_KEY_GENERATOR = "AES";
private final static int IV_LENGTH = 16;
private static SecretKey encryptionKey;
private static SecretKey decryptionKey;
private static AlgorithmParameterSpec paramSpec;
private final static int DEFAULT_READ_WRITE_BLOCK_BUFFER_SIZE = 1024;
private final static String ALGO_FILE_ENCRYPTER = "AES/CBC/PKCS5Padding";
@SuppressWarnings("resource")
public static void encrypt(SecretKey key, AlgorithmParameterSpec paramSpec, InputStream in, OutputStream out)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException {
try {
Cipher c = Cipher.getInstance(ALGO_FILE_ENCRYPTER);
c.init(Cipher.ENCRYPT_MODE, key, paramSpec);
out = new CipherOutputStream(out, c);
int count = 0;
byte[] buffer = new byte[DEFAULT_READ_WRITE_BLOCK_BUFFER_SIZE];
while ((count = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
} finally {
out.close();
}
}
@SuppressWarnings("resource")
public static void decrypt(SecretKey key, AlgorithmParameterSpec paramSpec,
InputStream in, OutputStream out)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IOException {
try {
Cipher c = Cipher.getInstance(ALGO_FILE_ENCRYPTER);
c.init(Cipher.DECRYPT_MODE, key, paramSpec);
out = new CipherOutputStream(out, c);
int count = 0;
byte[] buffer = new byte[DEFAULT_READ_WRITE_BLOCK_BUFFER_SIZE];
while ((count = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
} finally {
out.close();
}
}
private static void generateKeys() {
encryptionKey = null;
try {
encryptionKey = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] keyData = encryptionKey.getEncoded();
decryptionKey = new SecretKeySpec(keyData, 0, keyData.length, ALGO_SECRET_KEY_GENERATOR);
byte[] iv = new byte[IV_LENGTH];
try {
SecureRandom.getInstance(ALGO_RANDOM_NUM_GENERATOR).nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
paramSpec = new IvParameterSpec(iv);
}
}
Чего я ожидаю добиться, так это того, что при загрузке файла он должен успешно шифроваться и сохраняться во внутреннем хранилище. И когда я захочу, я могу расшифровать его в любое время.
РЕДАКТИРОВАТЬ: Я использую класс EncryptionUtils
, как это ...
generateKeys();
final File inputFile = new File(EXTERNAL_STORAGE_PATH + File.separator + RESOURCE_DIRECTORY_NAME + File.separator + pdfSlug + ".pdf");
final File encFile = new File(EXTERNAL_STORAGE_PATH + File.separator + RESOURCE_DIRECTORY_NAME + File.separator + "enc_file.enc");
try {
EncryptionUtils.encrypt(encryptionKey, paramSpec, new FileInputStream(inputFile), new FileOutputStream(encFile));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IOException e) {
Log.d(TAG, e.getLocalizedMessage());
}