package code;
public class T3 {
private final static int ENCODE_XORMASK = 0x5A; // 十六进制 90
private final static char ENCODE_DELIMETER = '\002'; // \转义字符 stx
private final static char ENCODE_CHAR_OFFSET1 = 'A';
private final static char ENCODE_CHAR_OFFSET2 = 'h';
public static void main(String[] args) {
System.out.println(T3.encodePasswordCookie("chen", "chen"));
System.out.println(T3.decodePasswordCookie("JkDkJkDkMmMkIhEhMh"));
}
private static String encodePasswordCookie(String username, String password)
{
StringBuffer buf = new StringBuffer();
if (username != null && password != null) {
byte[] bytes = (username + ENCODE_DELIMETER + password).getBytes(); //String.getBytes()使用给定的 charset 将此 String
//编码到 byte 序列,并将结果存储到新的 byte 数组对象
int b;
for (int n = 0; n < bytes.length; n++) {
b = bytes[n] ^ (ENCODE_XORMASK + n); // ^ 表示异或
buf.append((char)(ENCODE_CHAR_OFFSET1 + (b & 0x0F))); //& 与
buf.append((char)(ENCODE_CHAR_OFFSET2 + ((b >> 4) & 0x0F))); //>>右移
}
}
return buf.toString();
}
private static String[] decodePasswordCookie( String cookieVal ) {
// check that the cookie value isn't null or zero-length
if( cookieVal == null || cookieVal.length() <= 0 ) {
return null;
}
// unrafel the cookie value
char[] chars = cookieVal.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int b;
for (int n = 0, m = 0; n < bytes.length; n++) {
b = chars[m++] - ENCODE_CHAR_OFFSET1;
//m开始为0
b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
//m开始为1
bytes[n] = (byte)(b ^ (ENCODE_XORMASK + n));
}
cookieVal = new String(bytes);
int pos = cookieVal.indexOf(ENCODE_DELIMETER);
String username = (pos < 0) ? "" : cookieVal.substring(0, pos);
String password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
//添加一个输出测试
System.out.println("用户名:"+username+"\n"+"密码:"+password);
return new String[] {username, password};
}
}
结果:
JkDkJkDkMmMkIhEhMh
用户名:chen
密码:chen
用表格分析encode
字符 | ASCII | ENCODE_XORMASK+n | 二^三列的运算结果(异或) |
c | 1100011 | 1011010 n=0 | 111001 |
h | 1101000 | 1011011 n=1 | 110011 |
e | 1100101 | 1011100 | 111001 |
n | 1101110 | 1011101 | 110011 |
\002 stx | 0000010 | 1011110 | 1011100 |
c | 1100011 | 1011111 | 111100 |
h | 1101000 | 1100000 | 1000 |
e | 1100101 | 1100001 | 100 |
n | 1101110 | 1100010 | 1100 |
b = bytes[n] ^ (ENCODE_XORMASK + n); //上表的第四列结果
//第一个append的是 b的低4位 +'A' =X
buf.append((char)(ENCODE_CHAR_OFFSET1 + (b & 0x0F))); //& 与
//第二个append的是 b的高4为 +'h' =Y
buf.append((char)(ENCODE_CHAR_OFFSET2 + ((b >> 4) & 0x0F))); //>>右移
decode译码过程(X-'A')|[(Y-'h')<<4] 最终再一个异或