OCaml中的HMAC-SHA1签名?

时间:2017-08-03 18:10:18

标签: twitter ocaml sha1 hmac reason

我正在尝试向Twitter API发出请求,他们要求我签署我的请求。最后一部分需要通过HMAC-SHA1哈希算法进行签名。有没有简单的方法来获得它?

1 个答案:

答案 0 :(得分:1)

Hannes伸出手给我答案(在下面的ReasonML语法中,而不是OCaml):

Nocrypto.Hash.SHA1.hmac key::(Cstruct.of_string signingKey) (Cstruct.of_string output) |> Cstruct.to_string

有了这个,这是一个从Twitter API doc翻译的签名函数(参数和值也从该页面获取,因此输出可以验证为正确):

let signRequest clientId clientSecret method uri params :string => {
  let tmp = params |> List.sort (fun (a, _) (b, _) => compare a b);
  let collectedParamsString =
    List.map
      (
        fun (header: string, values: list string) => {
          let nextStr =
            List.fold_left
              (
                fun innerAcc value => {
                  let nextItem =
                    /* Using `Userinfo here is weird, but it's the only component I could get to properly percent-encode things in the same way Twitter expects it */
                    Uri.pct_encode component::`Query_key header ^
                    "=" ^ Uri.pct_encode component::`Userinfo value;
                  let final = innerAcc @ [nextItem];
                  print_endline (value ^ " => " ^ String.concat "&" final);
                  final
                }
              )
              []
              values |>
            String.concat "&";
          nextStr
        }
      )
      tmp |>
    String.concat "&";
  let output =
    String.uppercase_ascii method ^
    "&" ^
    Uri.pct_encode component::`Userinfo uri ^
    "&" ^ Uri.pct_encode component::`Userinfo collectedParamsString;
  let signingKey =
    Uri.pct_encode component::`Userinfo clientId ^
    "&" ^ Uri.pct_encode component::`Userinfo clientSecret;
  Cstruct.to_string (
    Nocrypto.Hash.SHA1.hmac key::(Cstruct.of_string signingKey) (Cstruct.of_string output)
  )
};

let signature =
  signRequest
    "post"
    "https://api.twitter.com/1.1/statuses/update.json"
    "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw"
    "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE"
    [
      ("status", ["Hello Ladies + Gentlemen, a signed OAuth request!"]),
      ("include_entities", ["true"]),
      ("oauth_consumer_key", ["xvz1evFS4wEEPTGEFPHBog"]),
      ("oauth_nonce", ["kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"]),
      ("oauth_signature_method", ["HMAC-SHA1"]),
      ("oauth_timestamp", ["1318622958"]),
      ("oauth_token", ["370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"]),
      ("oauth_version", ["1.0"])
    ];
/* let signature : string = "hCtSmYh+iHYCEqBWrE7C7hYmtUk */

编辑:我最初声称Hannes是OCaml的nocrypto库的作者 - 实际上是David Kaloper。非常抱歉,感谢DanielBünzli指出这一点!