如果你的api服务安全认证协议中要求使用hmac_sha1方法对信息进行编码,
而你的服务是由php实现的,客户端是由java实现的,那么为了对签名正确比对,就需要在两者之间建立能匹配的编码方式.
php侧如下:
define('id','123456');define('key','k123456');$strtosign = test_string;$utf8str = mb_convert_encoding($strtosign, utf-8);$hmac_sha1_str = base64_encode(hash_hmac(sha1, $utf8str, key));$signature = urlencode($hmac_sha1_str);print_r($signature);
java侧需要注意如下几点:1. hmac_sha1编码结果需要转换成hex格式
2. java中base64的实现和php不一致,其中java并不会在字符串末尾填补=号以把字节数补充为8的整数
3. hmac_sha1并非sha1, hmac_sha1是需要共享密钥的
参考实现如下:
import java.io.unsupportedencodingexception;import javax.crypto.mac;import javax.crypto.spec.secretkeyspec;import org.apache.wicket.util.crypt.base64urlsafe;public class test { public static void main(string[] args) { string key = f85b8b30f73eb2bf5d8063a9224b5e90; string tohash = get+\n+thu, 09 aug 2012 13:33:46 +0000+\n+/apichannel/report.m; //string tohashutf8 = urlencoder.encode(tohash, utf-8); string res = hmac_sha1(tohash, key); //system.out.print(res+\n); string signature; try { signature = new string(base64urlsafe.encodebase64(res.getbytes()),utf-8); signature = appendequalsign(signature); system.out.print(signature); } catch (unsupportedencodingexception e) { e.printstacktrace(); } } public static string hmac_sha1(string value, string key) { try { // get an hmac_sha1 key from the raw key bytes byte[] keybytes = key.getbytes(); secretkeyspec signingkey = new secretkeyspec(keybytes, hmacsha1); // get an hmac_sha1 mac instance and initialize with the signing key mac mac = mac.getinstance(hmacsha1); mac.init(signingkey); // compute the hmac on input data bytes byte[] rawhmac = mac.dofinal(value.getbytes()); // convert raw bytes to hex string hexbytes = byte2hex(rawhmac); return hexbytes; } catch (exception e) { throw new runtimeexception(e); } } private static string byte2hex(final byte[] b){ string hs=; string stmp=; for (int n=0; n
iefreer