数据加密之异或加密算法

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

  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

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值