如何使用以下示例使用Android解密aes文件?
我的目标是在Android应用程序的assets文件夹中以epub格式存储一组AES加密电子书,并在需要时对其进行解密,并使用nl.siegmann.epublib类在webviewer中显示它们。
我使用AES Crypt(https://www.aescrypt.com)使用与Java源代码相同的16个字符代码加密epub文件。一旦编译它需要一段时间但资产文件似乎解密,存储在本地临时文件中,然后使用epublib进行解析。然而,没有任何东西出现。我也注意到文件长度不同但我不确定我是否正确阅读。
我对Android开发很新,并且正在使用Android Studio 3.1.2
顺便说一下,加密的原因是文件必须存储在本地,而发布商想要一种方法(尝试并阻止)复制他们的epub书籍。加密密钥在工作时会更好地隐藏。提前谢谢。
package com.example.ebook;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubReader;
public class MainActivity extends AppCompatActivity {
private final String KEY = "1234567890123456";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
decryptFile();
}
public void decryptFile(){
WebView webView = findViewById(R.id.webView);
try {
String filename = "AccordingToLuke_9781874584292.epub.aes";
String filePath = "ebooks/";
// Get encrypted file from /assets
AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open(filePath + filename);
Integer fileLength = inputStream.toString().length();
// Create temp file to hold decrypted byte array
File tmp = File.createTempFile("tmp", "decrypted", getCacheDir());
tmp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmp);
SecretKeySpec sks = new SecretKeySpec(KEY.getBytes(),"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(inputStream, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
// Load book from tmp stream
FileInputStream fileInputStream = new FileInputStream(tmp);
Book book = (new EpubReader()).readEpub(fileInputStream);
Integer fileDecryptedLength = fileInputStream.toString().length();
// Display decrypted epub file
String contents = "";
String authors = book.getMetadata().getAuthors().toString();
contents = authors;
webView.loadData(contents,"text/html","utf-8");
} catch (Exception e) {
e.printStackTrace();
webView.loadData("Problem loading ebook","text/html","utf-8");
}
}
}