OCaml中的HMAC-SHA1签名?
答
汉纳斯伸出手来给我答案(在ReasonML语法下面,而不是OCaml的):
Nocrypto.Hash.SHA1.hmac key::(Cstruct.of_string signingKey) (Cstruct.of_string output) |> Cstruct.to_string
有了这样的,这里是从Twitter API doc(PARAMS翻译和值也采取了签字功能从该页面,以便输出可验证是正确的):
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库的作者 - 它实际上是大卫Kaloper。非常抱歉,并感谢DanielBünzli指出了这一点!
Hannes不是nocrypto的作者。 nocrypto的作者是David Kaloper。看到https://opam.ocaml.org/packages/nocrypto/ –
一旦我从'Nocrypto.Hash.SHA1.hmac'得到了输出,我需要通过B64.encode运行它以使'hCtSmYh + iHYCEqBWrE7C7hYmtUk ='匹配你的测试用例。 –