0
我正在使用Cipher/CipherInputStream来加密和解密Android中的数据库文件(sqlite)以进行备份。
当我使用没有密码的FileInputStream时,它工作得很好。但是,当我使用密码时,文件会成功加密,但是当我解密(恢复)它时,数据库不会解密为原始“源代码”。
原始caracteres(源代码)似乎是一个表意文字/象形文字/汉字(我不知道),当我加密和解密时,“源代码”是sql(英语)恢复OO
这使得'数据库损坏'使用FileInputStream/Cipher在Android中加密/解密数据库文件
才澄清
备份
File dbFile = new File(PATH_DB);
FileInputStream fileInputStream = new FileInputStream(PATH_DB);
FileOutputStream outputStream = new FileOutputStream(PATH_BKP);
byte[] s = Arrays.copyOf(KEY_DATABASE.getBytes(),16);
SecretKeySpec sks = new SecretKeySpec(s, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);
//Transferencia dos dados do inputfile para o output
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer))!= -1) {
cos.write(buffer,0,length);
}
//Fecha as streams
cos.flush();
cos.close();
fileInputStream.close();
还原:
FileInputStream fis = new FileInputStream(PATH_BKP);
FileOutputStream fos = new FileOutputStream(PATH_DB);
byte[] s = Arrays.copyOf(KEY_DATABASE.getBytes(),16);
SecretKeySpec sks = new SecretKeySpec(s, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream (fis, cipher);
byte[] buffer = new byte[1024];
int length;
while ((length = cis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
cis.close();
太好了!谢谢!它像一个魅力^^ – Jhon