您的位置:首页 > 编程语言 > Java开发

图片,音频,视频的文件加密,解密,保护自身资源

2017-01-03 18:34 766 查看
       private static String PASSWORD = "123456";     

文件加密方法,支持MP3,jpg,png,wav.rmvb等所有图片,音频,视频格式

亲测可用

/**

*文件路径

*输出路径

*/

public static void unCode(String filePath, String cachePath) {
InputStream is = null;
OutputStream out = null;
try {
File file = new File(filePath);
if (!file.exists()) {
return;
}
File dest = new File(cachePath);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
is = new FileInputStream(filePath);
out = new FileOutputStream(cachePath);

byte[] buffer = new byte[1024];
byte[] buffer2 = new byte[1024];
byte bMax = (byte) 255;
long size = file.length() - PASSWORD.length();
int mod = (int) (size % 1024);
int div = (int) (size >> 10);
int count = mod == 0 ? div : (div + 1);
int k = 1, r;
while ((k <= count && (r = is.read(buffer)) > 0)) {
if (mod != 0 && k == count) {
r = mod;
}
for (int i = 0; i < r; i++) {
byte b = buffer[i];
buffer2[i] = b == 0 ? bMax : --b;// 文件的每一个byte减1
}
out.write(buffer2, 0, r);
k++;
}
} catch (Exception e) {
} finally {
try {
if (out != null) {
out.close();
}
if (is != null) {
is.close();
}
} catch (Exception e2) {

}
}
}

====================机智的分割线==================================

文件解密方法,亲测可用

两个参数:1.文件路径

                  2.输出路径

public static void enCode(String filePath, String toPath) {
InputStream in = null;
OutputStream out = null;
try {
File file = new File(filePath);
if (!file.exists()) {
return;
}
in = new FileInputStream(filePath);
out = new FileOutputStream(toPath);
byte[] buffer = new byte[1024];
byte[] buffer2 = new byte[1024];
int r;
while ((r = in.read(buffer)) > 0) {
for (int i = 0; i < r; i++) {
byte b = buffer[i];
buffer2[i] = b == 255 ? 0 : ++b;// 文件的每一byte增1
}
out.write(buffer2, 0, r);
out.flush();
}
appendTail(toPath, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e2) {
}
}
}

/**
* 在文件尾添加指定的字符串

* @param fileName
* @param content
*/
private static void appendTail(String fileName, String content) {
try {
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐