XORUtils
/**
* Created by GuanSong
* on 2020/6/17
* Description:異或加密
* 某個字符或者數值 x 與一個數值 m 進行異或運算得到 y ,
* 則再用 y 與 m 進行異或運算就可還原爲 x
* 使用場景:
* 1、兩個變量的互換(不借助第三個變量)
* 2、數據的簡單加密解密
*/
public class XORUtils {
/**
* 固定key方式加解密
*
* @param data 原字符串
* @param key
* @return
*/
public static String encrypt(String data, int key) {
// if (TextUtils.isEmpty(data)) {
// return "";
// }
byte[] dataBytes = data.getBytes();
int length = dataBytes.length;
for (int i = 0; i < length; i++) {
dataBytes[i] ^= key;
}
final String dest = new String(dataBytes);
return dest;
}
/**
* 不固定key方式加密
*
* @param bytes 原字節數組
* @return
*/
public 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方式解密
*
* @param bytes 原字節數組
* @return
*/
public byte[] decrypt(byte[] bytes) {
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;
}
}
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
@Test
public void testEncrypt() {
System.out.println("oneplus = " + XORUtils.encrypt("oneplus", 8));
}
}