背景
最近在测试公司软件的一个功能,它会读取一个配置文件信息,但是配置文件做了个加密处理,处理的方式就是所有的字节都取反。这个是一个很简单的功能,结果却花了好一会儿 主要还是基础太薄弱了,mark一下吧
实现
这里就直接贴代码吧
public static void main(String[] args) throws IOException {
byte[] bytes = toByteArray("C:\\config.ini");
byte temp;
for(int i=0;i<bytes.length;i++){
temp = bytes[i];
bytes[i] = (byte) (~temp);
}
System.out.println(new String(bytes,"gbk"));
}
/**
* the traditional io way
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filename) throws IOException{
File f = new File(filename);
if(!f.exists()){
throw new FileNotFoundException(filename);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length());
BufferedInputStream in = null;
try{
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while(-1 != (len = in.read(buffer,0,buf_size))){
bos.write(buffer,0,len);
}
return bos.toByteArray();
}catch (IOException e) {
e.printStackTrace();
throw e;
}finally{
try{
in.close();
}catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
我们这里读取的就是一个Config.ini文件,接着需要读取文件的后获取到它的byte数组。取反的方法直接采用java自带的~就可以了。结果还百度了半天,因为是用gbk编码,所以说转换成String类型的时候需要说明编码类型,不然转码就是乱码了。