背景
最近遇到了一个上传身份证的需求, 担心用户身份证泄露,所以对用户身份证信息进行异或加密,网上的异或方式用固定的key加密, 即使拿到加密图片也很容易破解, 于是乎灵机一动,写下不容易被破解key的办法,分享给有类似诉求的朋友:
直接上代码
public class Demo {
public static void main(String[] args) throws Exception {
String source = "/home/xxx/develop/111.jpeg";
String target = "/home/xxx/develop/222.jpeg";
String decode = "/home/xxx/develop/333.jpeg";
encode(source, target);
encode(target, decode);
printHead(target, 32);
}
public static void encode(String source, String target) throws Exception {
int[] key = {5,4,3,2,1,1,2,3,4,5,6,7,8,9,1}; //随意设置
System.out.println("");
File inFile = new File(source);
File outFile = new File(target);
FileInputStream input = new FileInputStream(inFile);
FileOutputStream output = new FileOutputStream(outFile);
int i = 0;
int j = 0;
int content = 0;
while ((content = input.read()) != -1) {
i++;
if (i <= 32) { //为了跳过文件头
System.out.print(content + " ");
output.write(content);
} else {
j++;
int index = j % key.length;
output.write(content ^ key[index]);
}
}
//关闭资源
output.close();
input.close();
}
public static void printHead(String source, int size) throws Exception {
System.out.println("");
File inFile = new File(source);
FileInputStream input = new FileInputStream(inFile);
int i = 0;
int content = 0;
while ((content = input.read()) != -1 && i < size) {
i++;
System.out.print(content + " ");
}
//关闭资源
input.close();
}
}