使用java编程实现明文和密文之间的互转

原理是异或加密 

1
2
3
4
5
6
7
8
9
10
11
    char c[] = "大家好".toCharArray();
    for(int i = 0;i<c.length;i++) {
    	c[i] = (char)(c[i] ^ 'Q');//将明文转换成密文
    }
    String string = new String(c, 0, c.length);
    System.out.println("密文:" + string);
    for(int i=0;i<c.length;i++) {
    	c[i] = (char)(c[i] ^ 'Q');//将密文还原为明文
    }
    String string1 = new String(c, 0, c.length);
    System.out.println("明文:" + "\n" + string1);

上面这个没有用户密钥,能直接解密,我们来升级一下

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
import java.nio.charset.Charset;
 
 
public class DeEnCode {
 
	private static final String key0 = "FECOI()*&<MNCXZPKL";
	private static final Charset charset = Charset.forName("UTF-8");
	private static byte[] keyBytes = key0.getBytes(charset);
	
	public static String encode(String enc){
		byte[] b = enc.getBytes(charset);
		for(int i=0,size=b.length;i<size;i++){
			for(byte keyBytes0:keyBytes){
				b[i] = (byte) (b[i]^keyBytes0);
			}
		}
		return new String(b);
	}
	
	public static String decode(String dec){
		byte[] e = dec.getBytes(charset);
		byte[] dee = e;
		for(int i=0,size=e.length;i<size;i++){
			for(byte keyBytes0:keyBytes){
				e[i] = (byte) (dee[i]^keyBytes0);
			}
		}
		return new String(e);
	}
 
	public static void main(String[] args) {
		String s="you are right";
		String enc = encode(s);
		String dec = decode(enc);
		System.out.println(enc);
		System.out.println(dec);
	}
}

现在你就可以自定义key,增加难度,但是这个还是不安全,密钥还是可能被套取,所以加入当前时间,这样每次生成的密钥都不一样

坚持原创技术分享,您的支持将鼓励我继续创作!