如何生成HMAC-SHA1签名的机器人? [英] How to generate HMAC-SHA1 Signature in android?
本文介绍了如何生成HMAC-SHA1签名的机器人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的基本字符串:
String args ="oauth_consumer_key="+enc(consumerkey) +
"&oauth_nonce="+enc(generateNonce()) +
"&oauth_signature_method=HMAC-SHA1" +
"&oauth_timestamp="+ timestamp +
"&oauth_token="+enc(Home.consToken) +
"&oauth_verifier="+verifier+"&oauth_version=1.0";
String base ="POST&"+enc("https://api.linkedin.com/uas/oauth /accessToken") +"&"+ enc(args);
String signature =computeHmac(base,consumer_secret+"&"+secretToken);
这是我的头:
String header = "OAuth " +
"oauth_consumer_key=\""+ enc(consumerkey)+ "\"," +
"oauth_nonce=\""+ enc(generateNonce()) + "\"," +
"oauth_signature_method=\"HMAC-SHA1\"," +
"oauth_timestamp=\""+ timestamp + "\"," +
"oauth_token=\""+Home.consToken + "\"," +
"oauth_signature=\""+enc(signature)+"\","+
"oauth_verifier=\""+verifier +"\","+
"oauth_version=\""+1.0+"\"" ;
我使用下面的方法来生成签名:
I am using following method to generate Signature:
public String computeHmac(String baseString, String key)
throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException
{
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
mac.init(secret);
byte[] digest = mac.doFinal(baseString.getBytes());
byte[] result=Base64.encodeBase64(digest);
return new String(result);
}
在执行此codeI正在以下错误...
while executing this code i am getting the following error...
oauth_problem=signature_invalid&
oauth_problem_advice=com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException
任何人可以帮助我呢?
can anybody help me out this?
谢谢...
推荐答案
费米的答案是绝对正确的,但是,这不是很明显,我究竟是什么 INTVAL(B)
。我的理解是 B和; 0xFF的
。
Femi's answer is absolutely correct, however, it wasn't obvious for me what exactly is intval(b)
. As i understood it's b & 0xFF
.
我也应用了一些优化(我发现<一href="http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java">here)这里是我的code:
Also I applied some optimizations (that I found here) and here is my code:
private static String hmacSha1(String value, String key)
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException {
String type = "HmacSHA1";
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
Mac mac = Mac.getInstance(type);
mac.init(secret);
byte[] bytes = mac.doFinal(value.getBytes());
return bytesToHex(bytes);
}
private final static char[] hexArray = "0123456789abcdef".toCharArray();
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
这篇关于如何生成HMAC-SHA1签名的机器人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文