Java使用异或运算实现简单的加密解密算法实例代码

时间:2022-08-26 13:12:20

Java简单的加密解密算法,使用异或运算

实例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
package cn.std.util;
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);
    }
}

实例2

?
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
public static String setEncrypt(String str){
    String sn="ziyu";
    //密钥
    int[] snNum=new int[str.length()];
    String result="";
    String temp="";
    for (int i=0,j=0;i<str.length();i++,j++){
        if(j==sn.length())
                j=0;
        snNum[i]=str.charAt(i)^sn.charAt(j);
    }
    for (int k=0;k<str.length();k++){
        if(snNum[k]<10){
            temp="00"+snNum[k];
        } else{
            if(snNum[k]<100){
                temp="0"+snNum[k];
            }
        }
        result+=temp;
    }
    return result;
}
public static String getEncrypt(String str){
    String sn="ziyu";
    //密钥
    char[] snNum=new char[str.length()/3];
    String result="";
    for (int i=0,j=0;i<str.length()/3;i++,j++){
        if(j==sn.length())
                j=0;
        int n=Integer.parseint(str.substring(i*3,i*3+3));
        snNum[i]=(char)((char)n^sn.charAt(j));
    }
    for (int k=0;k<str.length()/3;k++){
        result+=snNum[k];
    }
    return result;
}
}

总结

以上就是本文关于Java使用异或运算实现简单的加密解密算法实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/a1049107922/article/details/52413693