数据加密之异或加密算法

对于异或运算,使用的比较多的应该是两个数进行交换,这里,要说的是对数据进行加密。

  1. 使用一个固定的key进行加密,这时的加密和解密过程的一样的:
public static void main(String[] args) {
	String name = "数据加密之异或加密算法";
	byte[] encrypt = encrypt(name.getBytes());
	System.out.println(new String(encrypt));
	System.out.println(new String(decrypt(encrypt)));

}
public static byte[] encrypt(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        int len = bytes.length;
        int key = 0x13;
        for (int i = 0; i < len; i++) {
            bytes[i] ^= key;
        }
        return bytes;
}

输出结果:

仫盐募俐┼盐亳ズ
数据加密之异或加密算法
  1. 使用不固定的key进行加密,这是加密和解密过程是不一样的:
public static void main(String[] args) {
	String name = "数据加密之异或加密算法";
	byte[] encrypt = encrypt(name.getBytes());
	System.out.println(new String(encrypt));
	System.out.println(new String(decrypt(encrypt)));
}
	
public static byte[] encrypt(byte[] bytes) {
	 if (bytes == null) {
	       return null;
	 }
	 int len = bytes.length;
	 int key = 0x13;
         for (int i = 0; i < len; i++) {
	      bytes[i] ^= key;
	      key = bytes[i];
	 }
	 return bytes;
}
	
public static byte[] decrypt(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        int len = bytes.length;
        int key = 0x13;
        for (int i = len - 1; i > 0; i--) {
            bytes[i] ^= bytes[i - 1];
        }
        bytes[0] ^= key;
        return bytes;
}

看下输出:

?$欸?(?7酧漲?8刉擧僠?
数据加密之异或加密算法

这对于一般的数据加密还是挺好用的,再者异或运算的效率高。

参考:http://www.cnblogs.com/whoislcj/p/5944917.html

猜你喜欢

转载自blog.csdn.net/tangedegushi/article/details/82256252