有时候在程序中需要考虑安全的问题,要对一些内容进行加密。这里给出一个简单的加密和解密的算法,就是对给出的字符数组进行二进制取反操作。
public class SimpleEncryption {
/**
* <pre>
* 加密数组,将buff数组中的么个字节的每一位取反。
* @param buff
* @return
* </pre>
*/
public static final byte[] encryption(byte[] buff) {
for (int i = 0, j = buff.length; i < j; i++) {
int temp = 0;
for (int m = 0; m < 9; m++) {
int bit = (buff[i] >> m & 1) == 0 ? 1 : 0;
temp += (1 << m) * bit;
}
buff[i] = (byte) temp;
}
return buff;
}
/**
* @param args
*/
public static void main(String[] args) {
String hello = "QW12#$";
System.out.println("before encryption:\t" + hello); // QW12
byte[] one = encryption(hello.getBytes());
System.out.println("after encryption:\t" + new String(encryption(one))); // QW12
}
}