如何在另一设备的同款App中解密共享的加密存储文件
问题描述
为保障App存储安全,我使用EncryptedStorage对存储进行加密,代码如下:
EncryptedStorage.install("your-pass-encryption-key")
我创建了一个文本文件打算共享到另一设备的同款App中使用,但该文件无法在另一设备打开,提示文件已加密。
请问如何解密该文件,使其能在另一设备的同款App中打开使用?
补充说明
我通过以下代码将文件保存为.txt格式,以便使用plain/text MIME类型进行共享:
String databasePath = Display.getInstance().getDatabasePath("TestDB.db"); String mimeType = "application/vnd.sqlite3"; mimeType = "application/x-sqlite3"; mimeType = "plain/text"; try { FileSystemStorage fss = FileSystemStorage.getInstance(); InputStream is = fss.openInputStream(databasePath); //Copy from FSS to Storage Util.copy(is, Storage.getInstance().createOutputStream("TestDB.txt")); String fileToSharePath = FileSystemStorage.getInstance().getAppHomePath() + "TestDB.txt"; Log.p("FileToSharePath " + fileToSharePath); Display.getInstance().share(fileToSharePath, null, mimeType); } catch (IOException e) { Log.p("Share error: " + e); }
我在另一设备通过以下代码使用FileChooser浏览共享文件,并将其保存为.db文件到App数据库目录:
FileChooser.showOpenDialog("txt", ev -> { if (ev == null) { Log.p("no file selected"); } else { String filePath = (String) ev.getSource(); Log.p("FilePath " + filePath); try { FileSystemStorage fss = FileSystemStorage.getInstance(); InputStream is = fss.openInputStream(filePath); String databasePath = Display.getInstance().getDatabasePath("TestDB.db"); OutputStream os = FileSystemStorage.getInstance().openOutputStream(databasePath); Util.copy(is, os); } catch (IOException e) { Log.p("Create DB error: " + e); } } });
解决方案
问题出在共享文件时,你通过已被EncryptedStorage替换的Storage实例写入文件,导致内容被自动加密。要让另一设备的同款App能打开,需在共享前输出明文内容,而非加密后的内容。
1. 修改共享端代码,直接生成明文共享文件
不要通过Storage中转,直接用FileSystemStorage复制原始数据库文件到共享路径,确保写入的是明文:
String databasePath = Display.getInstance().getDatabasePath("TestDB.db"); String mimeType = "plain/text"; try { FileSystemStorage fss = FileSystemStorage.getInstance(); String fileToSharePath = fss.getAppHomePath() + "TestDB.txt"; // 直接复制原始数据库文件到共享路径,绕过加密的Storage InputStream is = fss.openInputStream(databasePath); OutputStream os = fss.openOutputStream(fileToSharePath); Util.copy(is, os); // 关闭流释放资源 is.close(); os.close(); Log.p("FileToSharePath " + fileToSharePath); Display.getInstance().share(fileToSharePath, null, mimeType); } catch (IOException e) { Log.p("Share error: " + e); }
说明:EncryptedStorage仅替换默认的Storage实现,FileSystemStorage是直接操作本地文件系统的工具,不会自动加密内容,因此直接复制得到的是明文文件。
2. 接收端代码无需额外修改
接收端现有代码可以直接使用,只要接收的是明文文件,保存到数据库路径后,若接收端同样启用了EncryptedStorage(且密钥与发送端一致),App会自动对该文件进行加密存储,不影响后续使用。
额外注意
- 若需在共享过程中保障文件安全,可手动用对称加密算法(如AES)加密文件,接收端用相同密钥解密后再保存,避免明文传输风险。
- 发送端与接收端必须使用完全相同的加密密钥,否则接收端启用
EncryptedStorage后无法正常读取文件。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

