Android数据安全之异或加密

来源:互联网 发布:linux线程安全退出 编辑:程序博客网 时间:2024/05/21 09:30

异或运算中,如果某个字符(或数值)x 与 一个数值m 进行异或运算得到y,则再用y 与 m 进行异或运算就可以还原为 x ,因此应用这个原理可以实现数据的加密解密功能。

完整代码参考github:Android-Encrypt-master

使用场景

两个变量的互换(不借助第三个变量)数据的简单加密解密

代码实现

1.固定key的方式

/** * 固定key的方式 */public static byte[] encrypt1(byte[] bytes) {    if (bytes == null) {        return null;    }    int len = bytes.length;    int key = 0x12;    for (int i = 0; i < len; i++) {        bytes[i] ^= key;    }    return bytes;}

2.不固定key的方式

/** * 不固定key的加密方式 (推荐使用不固定key) */public static byte[] encrypt(byte[] bytes) {    if (bytes == null) {        return null;    }    int len = bytes.length;    int key = 0x12;    for (int i = 0; i < len; i++) {        bytes[i] = (byte) (bytes[i] ^ key);        key = bytes[i];    }    return bytes;}/** * 对应不固定key的解密方式 */public static byte[] decrypt(byte[] bytes) {    if (bytes == null) {        return null;    }    int len = bytes.length;    int key = 0x12;    for (int i = len - 1; i > 0; i--) {        bytes[i] = (byte) (bytes[i] ^ bytes[i - 1]);    }    bytes[0] = (byte) (bytes[0] ^ key);    return bytes;}

3测试

private String data = "这是一个测试编码和加解密的字符串数据"private boolean isXorEncrypt = true;/** * 异或加密算法 */private void xorEncrypt() {    if (isXorEncrypt) {        encryptXor = XORUtils.encrypt(data.getBytes());        Log.d("TAG:"+TAG,"----XOR异或加密: "+Base64.encodeToString(encryptXor,Base64.DEFAULT));        tvContent.setText("XOR异或加密: "+Base64.encodeToString(encryptXor,Base64.DEFAULT));    }else {        byte[] decryptXor = XORUtils.decrypt(encryptXor);        Log.d("TAG:" + TAG, "----XOR异或解密: " + new String(decryptXor));        tvContent.setText("XOR异或解密: " + new String(decryptXor));    }    isXorEncrypt = !isXorEncrypt;}

追及

位运算可以实现很多高级,高效的运算。比如说加密,乘法中的n次方就是右移n位,速度还快。IM二进制数据包采用异或算法第一能够实现加密,第二采用异或加密算法不会改变二进制数据的长度这对二进制数据包封包起到不小的好处。

1 0