AK/SK认证方式

AK/SK认证是对请求消息按照一定规则生成签名信息,服务器对签名信息进行安全认证,主要作用是保证请求的可靠性,完整性。

ak表示公钥,sk表示私钥。ak与sk一一对应,不同的域使用不同的aksk.

下面提供一个简单的签名认证方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class AKSKImpl {

private static String AK="123456789";

private static String SK="012345";

public static void main(String[] args) throws Exception {
String str= sign("1234.do","11111111","11111",AK,SK);
System.out.println(str);
}

private static String sign(String url,String dateTime,String numNoice,String ak,String sk) throws Exception{
String data= ak+url +numNoice+dateTime;

String sign=hamcsha1(data.getBytes("UTF-8"),sk.getBytes("UTF-8"));

return sign;
}
public static String hamcsha1(byte[] data, byte[] key)
{
try {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
return byte2hex(mac.doFinal(data));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//二行制转字符串
public static String byte2hex(byte[] b)
{
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b!=null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
}