使用Hmac SHA1签署HTTP请求

时间:2014-08-31 12:25:06

标签: java javascript hmacsha1

我的REST API的授权模式包括一个HTTP标头,如下所示:

"Authorization: MyAuth: JWT_VALUE:207112ade53c795df43ce38e5251b41ded1791aa"

JWT_VALUE是一个标准的Json Web令牌,它还包含加密的API密钥作为自定义声明。冒号后面的第二部分是客户端生成的签名,如下所示:

<script src='lib/hmac-sha1.js' type='text/javascript'></script>

...

var token = ...
var signature = CryptoJS.HmacSHA1(token + httpMethod + requestUrl + requestBody), apiKey);
headers["Authorization"] = "MyAuth " + token + ":" + signature;

问题是我无法在服务器上生成相同的签名;这是我的Scala代码:

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64

...

val data = token + request.method + request.uri + request.body.asInstanceOf[AnyContent].asJson.getOrElse("")
val secret = ... // extract api key from token and decrypt it with app secret key

val singed = sign(data, secret)

if (signed != request.signature) {
  // error
  ...
}

...

def sign(data: String, secret: String): String = {
  val mac = Mac.getInstance("HmacSHA1")
  mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1"))
  Base64.encodeBase64String(mac.doFinal(data))
}

以下是我在调试会话中获得的示例:

Incoming request signed by the server =========> um/TemuwSzboWD1D4kLRnFD6Sxk=
Signature generated by the client =============> 1c0567113a6bcc9f3715b83182d62e11aff52cec

正如您所见,服务器使用javax.crypto.Mac生成的签名比使用CryptoJs的客户端生成的签名更短。

1 个答案:

答案 0 :(得分:0)

如Pavel所述,问题是我在客户端上使用了HEX表示,在服务器上使用了BASE64表示。为了解决这个问题,我刚刚修改了客户端:

<script src='lib/hmac-sha1.js' type='text/javascript'></script>
<script src='lib/enc-base64-min.js' type='text/javascript'></script>

...

var token = ...
var signature = CryptoJS.HmacSHA1(token + httpMethod + requestUrl + requestBody), apiKey).toString(CryptoJS.enc.Base64);
headers["Authorization"] = "MyAuth " + token + ":" + signature;

非常感谢帕维尔。