異或運算中,如果某個字符(或數值)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二進制數據包採用異或算法第一能夠實現加密,第二採用異或加密算法不會改變二進制數據的長度這對二進制數據包封包起到不小的好處。