搜狗的一道笔试题,关于加密解密的,很有意思!
原文地址:http://www.iteye.com/topic/1116115
?
?
这是一道搜狗的笔试题,要求30分钟。根据encode方法写出对应的decode方法。最后运行程序输出的结果就是要求的答案。先不看答案,trying一下吧。程序如下:?
public class Test {?
??? public static void encode(byte[] in, byte[] out, int password) {?
??????? int len = in.length;?
??????? int seed = password ^ 0x8c357ca5;?
??????? for (int i = 0; i < len; ++i) {?
??????????? byte a = (byte) ((in[i] ^ seed) >>> 5);?
??????????? byte b = (byte) (((((int) in[i]) << 16) ^ seed) >>> (16 - 3));?
??????????? a &= 0x7;?
??????????? b &= 0xf8;?
??????????? out[i] = (byte) (a | b);?
??????????? seed = (seed * 3687989 ^ seed ^ in[i]);?
??????? }?
??? }?
??? public static void decode(byte[] in, byte[] out, int password) {?
??????? int len = in.length;?
??????? int seed = password ^ 0x8c357ca5;?
??????? for (int i = 0; i < len; ++i) {?
??????????? // fill the code here?
??????? }?
??? }?
??? public static void main(String[] args) throws Exception {?
??????? int password = 0xe87dd9d3;?
??????? byte[] buf1 = { 29, -16, 96, 43, -85, 25, -96, 83, 13, 66, -109, 49, -111, 0, 60, -101, 99, -86, -38, 86, -35,?
??????????????? 48, 23, 83, -102, 25, 73, -116, -101, -88, -5, 14, -14, -112, 87, -87, 2, 108, -58, 40, 56, 12, 108,?
??????????????? 77, 83, 38, 20, -114, };?
??????? byte[] buf2 = new byte[buf1.length];?
??????? decode(buf1, buf2, password);?
??????? System.out.println(new String(buf2, "GBK"));?
??? }?
}?
----------------------?
最后输出结果是:搜狗输入法支持各种炫酷的皮肤,彰显个性的你!!!?
其中一种实现方式为:?
byte a = (byte) (((in[i]&0x7) <<5) ^seed);?
byte b = (byte) ((((((int) in[i])&0xf8) << 13) ^ seed) >>> 16);?
a &= 0xe0;?
b &= 0x1f;?
out[i] = (byte) (a | b);?
seed = (seed * 3687989 ^ seed ^ out[i]);