分类: Java
2012-01-09 21:23:51
Toptoken签名过程:
所需参数:nick = "lrblch"/*用户名*/,
appsec = “dc6e1cebc7bd7bf37c626a140043e0b7”,
appkey = “12316987”,
time = “1313672064”/*-- 这是时间t产生的例子,它是以秒为单位String.valueOf((new Date()).getTime() / 1000)--*/
(签名结果:b680f2186b3cae8ee9c0790b74c8272e)
签名过程:
1. 将appSec(GBK编码),做md5签名转成字节数组,取名为bytes1
2. 将bytes1转成16进制编码的字符数组,取名为char1
(每个byte转成2个char字符。第一个字符由byte与0xF0做与操作,得到高四位,右移四位,高位补0,得到高四位的字符;第二个字符由byte与0x0F做与操作,得到低四位 中间结果:a2a9b4a9e80d3949adc07f86198dd530)
3. 将appkey,char1,nick,time连接为字符串,再将之并转成GBK格式的字节数组,作为bytes2 (中间结果:[B@c2b2f6)
4. 将bytes2做md5签名,成为字节数组bytes3
5. 将bytes3按照步骤2同样的方法转为字符数组toptoken
6. 返回
简易流程示意:hex(md5(appkey+hex(md5(appSec))+nick+time))
Java代码示例:
public static final String genLoginTopToken(final String nick,
final String appSec, final String appKey, final long time) {
try {
return DigestUtils.md5Hex((appKey
+ DigestUtils.md5Hex(appSec.getBytes("GBK")) + nick + time)
.getBytes("GBK"));
} catch (UnsupportedEncodingException e) {
}
return " ";
}
其中md5Hex的签名过程,为先调用md5,然后是转16进制
(org.apache.commons.codec.digest.DigestUtils)
public static String md5Hex(byte[] data) {
return new String(Hex.encodeHex(md5(data)));
}
这个是用md5产生的字节流转16进制,一个字节转成两个char
(org.apache.commons.codec.binary.Hex)
public static char[] encodeHex(byte[] data) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS[(0xF0 & data[i]) >>> 4 ];
out[j++] = DIGITS[ 0x0F & data[i] ];
}
return out;
}
private static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};