欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java的简单加密和解密

程序员文章站 2024-03-13 23:04:53
...

    有时候在程序中需要考虑安全的问题,要对一些内容进行加密。这里给出一个简单的加密和解密的算法,就是对给出的字符数组进行二进制取反操作。

 

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
	}

}