我正在尝试使用此代码加密/解密存储在 sd 卡上的应用程序的 xml 文件。虽然加密工作正常,但我被困在解密部分。
加密代码:
private void writeToFile(final String xmlString, final String exportFileName) throws IOException {
File dir = new File(Environment.getExternalStorageDirectory(), BData.DATASUBDIRECTORY);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, exportFileName);
file.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
try {
String fileData = AdvancedCrypto.encrypt("myPassword", "mySalt"), xmlString.toString());
bos.write(fileData.getBytes());
} catch (Exception e){
} finally {
if (bos != null) {
bos.flush();
bos.close();
}
}
}
解密代码:
public void getDataFromXML(Context context, String fileName){
try
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser _xml = factory.newPullParser();
// get a reference to the file.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + fileName);
// create an input stream to be read by the stream reader.
FileInputStream fis = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(fis);
int size = (int) file.length();
byte[] contents = new byte[size];
//byte[] data = buf.read(contents);
String fileData = AdvancedCrypto.decrypt("myPassword", "mySalt"), contents.toString());
buf.read(fileData.getBytes());
// set the input for the parser using an InputStreamReader
_xml.setInput(buf, HTTP.UTF_8);
buf.close();
int eventType = _xml.getEventType();
boolean done = false;
//..rest of the code
}
}
它抛出这个错误:
07-07 21:44:27.755: W/System.err(5608): Caused by: java.lang.StringIndexOutOfBoundsException: length=11; regionStart=0; regionLength=32
07-07 21:44:27.755: W/System.err(5608): at java.lang.String.startEndAndLength(String.java:593)
07-07 21:44:27.755: W/System.err(5608): at java.lang.String.substring(String.java:1474)
在解密方法的这一行:
String ivHex = encrypted.substring(0, IV_LENGTH * 2);
我是否正确读取文件以解密它?