简书链接:异或加密解密以及暴力随机几千次的测试按原串索引进行解密验证
文章字数:190,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Random;

public class XorTest {
public static void main(String[] args) {
long encrypt_key=Long.MAX_VALUE;
long xor=encrypt_key^5000;
long reverse=xor^5000;
StringBuffer sb=new StringBuffer("abcdefghijklmnopqrstuvwxyz·~!@#$%^&*()_+-={}[]|\\:';',./?");
testRandomCount(sb.toString(), 500000);
System.out.println("执行完毕!");
int length=sb.length();
System.out.println("加密前长度:"+length+",数据:"+sb.toString());
StringBuffer encryptSb=new StringBuffer();
for(int i=0;i<length;i++){
encryptSb.append(makecodeChar(sb.substring(i,i+1), encrypt_key));
}

System.out.println("加密后长度:"+encryptSb.length()+",数据:"+encryptSb.toString());

StringBuffer decryptSb=new StringBuffer();
for(int i=0;i<length;i++){
decryptSb.append(makecodeChar(encryptSb.substring(i,i+1), encrypt_key));
}

System.out.println("解密后长度:"+decryptSb.length()+",数据:"+decryptSb.toString());







// new String(char(xor));
}

// 单个字符异或运算
private static String makecodeChar(String password, long randomkey) {
char[] array = password.toCharArray();// 获取字符数组
// 遍历字符数组
for (int i = 0; i < array.length; i++) {
array[i] = (char) (array[i] ^ randomkey);// 对每个数组元素进行异或运算,异或的值可以自己选择
}
return new String(array);
}


public static void testRandomCount(String encryptData,int count){
int index=0;
int length=encryptData.length();
while(index<count){
long encrypt_key=new Random().nextLong();
StringBuffer encryptSb=new StringBuffer();
for(int i=0;i<length;i++){
encryptSb.append(makecodeChar(encryptData.substring(i,i+1), encrypt_key));
}

// System.out.println("加密后长度:"+encryptSb.length()+",数据:"+encryptSb.toString());

StringBuffer decryptSb=new StringBuffer();
for(int i=0;i<length;i++){
decryptSb.append(makecodeChar(encryptSb.substring(i,i+1), encrypt_key));
}

if(!decryptSb.toString().equals(encryptData)){
throw new RuntimeException("无法解密,随机数:"+length+"数据不匹配:\n"+decryptSb.toString()+"\n"+encryptData);
}
index++;

}
}
}


验证结果,亦或操作不会影响字符串长度,可以根据原有未加密字符串按索引位进行解密。不支持显示的则显示?号。