使用加密文件并为它们提供 FileProvider

Work with encrypted file and provide them with FileProvider

在我的 Android 应用程序中,我需要从 FileProvider 公开一些文件。没有加密,这很简单:我只需将 FileProvider 添加到 manifest.xml.

<provider
   android:name="androidx.core.content.FileProvider"
   android:authorities="${applicationId}.provider"
   android:exported="false"
   android:grantUriPermissions="true">
   <meta-data
     android:name="android.support.FILE_PROVIDER_PATHS"
     android:resource="@xml/provider_paths" />
</provider>

我需要接收一些文件,对其进行加密(将其机密存储在数据库中),然后使用 FileProvider 公开它们。我该怎么做?

谢谢

您可以像 this question. Depending on the file type you want to serve and the app that should view it, you can pick a strategy, which is discussed a little in this question 那样推出自己的 FileProvider

例如,Word 应用程序可以很好地使用管道 ParcelFileDescriptor,对于图像,您可能需要创建文件的临时副本并提供该文件。

这是一个示例,说明它可能如何查找 Word 文件和类似文件:

@Nullable
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
    ParcelFileDescriptor[] pipe = null;
    try {
        pipe = ParcelFileDescriptor.createReliablePipe();
    } catch (IOException e) {
        Log.d(TAG, "Error creating pipe", e);
    }
    if (mode.contains("r")) {
        FileInputStream fis = FileEncryptionWrapper.getEncryptedFileInputStream(getContext(), uri);
        new PipeFeederThread(fis, new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1])).start();
        return pipe[0];
    } else if (mode.contains("w")) {
        FileOutputStream fos = FileEncryptionWrapper.getEncryptedFileOutputStream(getContext(), uri);
        new PipeFeederThread(new ParcelFileDescriptor.AutoCloseInputStream(pipe[0]), fos).start();
        return pipe[1];
    }
    return null;
}

它使用 PipeFeederThread 从您的流中获取内容到 reading/writing 端:

static class PipeFeederThread extends Thread {
    InputStream in;
    OutputStream out;

    PipeFeederThread(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    @Override
    public void run() {
        byte[] buf = new byte[8192];
        int len;

        try {
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            Log.e(TAG, "PipeFeederThread: Data transfer failed:", e);
        }
    }
}

FileProvider也需要在AndroidManifest.xml中声明:

<provider
    android:name=".InternalFileProvider"
    android:authorities="com.android.prototypes.encryptedimagefileprovider.InternalFileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
   <files-path name="files" path="./" />
</paths>

遗憾的是,到目前为止我还没有找到好的 "one size fits all" 解决方案,并且仍在搜索中。将不同类型的加密文件导出到其他应用程序似乎还没有以干净一致的方式解决。