3

2

##### MathematicaのHMAC（ハッシュベースのメッセージ認証コード、別名データ署名）

5

これが私の実装です：

```(* Pad the string s with x on the right/left so it has length n. *)
strpadr[s_, n_, x_] := [email protected][Characters[s], n, x]
strpadl[s_, n_, x_] := [email protected][Characters[s], n, x]

(* hex representation; optionally pad to length n with zeros *)

(* parse hex representation (return an integer) *)
unhex[x_] := FromDigits[x, 16]

(* Concatenate all the arguments as strings (if they're not already). *)
cat = StringJoin @@ (ToString /@ {##}) &;

(* Takes a string like "xy" and returns the hex representation (also a string,
twice as long) of the bytes (ascii codes). *)
tobytes[s_] := cat @@ (hex[#, 2] & /@ ToCharacterCode[s])

(* Takes a length n string like "0a10" and returns a length n/2 string where in
this example the first character is whatever has ascii code 10 ("a" in hex)
and the second is whatever has ascii code 16 ("10" in hex). *)
frombytes[hs_] := FromCharacterCode[unhex /@ [email protected]@@Partition[Characters[hs], 2]]

(* Bitwise-xor of two integers given in hex. *)
hexbitxor[a_String, b_String] := [email protected][[email protected], [email protected]]

(* Repeat the string s, n times. *)
strrpt[s_, n_] := cat @@ ConstantArray[s, n]

(* Byte length of a hex string is half the string length. *)
bytelen[s_] := Ceiling[StringLength[s]/2]```

Mathematicaで基本的なハッシュ関数を実装するのは簡単ではありません。 この質問を参照してください：https://stackoverflow.com/questions/1854491/cryptographic-hash[Mathematicaで文字列として与えられたデータの暗号化ハッシュ（sha1またはmd5）]。

```(* FileHash is the only way to hash data given as a string in Mma. *)
hash[s_String, h_:"SHA"] := Module[{stream = StringToStream[s], result},
result = FileHash[stream, h];
Close[stream];
[email protected]];
sha1[s_] := hash[s]
md5[s_] := hash[s, "MD5"]```

```(* Return the hmac digest using hash function h for string s with key k. *)
b = 64; (* block size for both md5 and sha1 *)
key = tobytes[k];
key = If[bytelen[key] > b, h[[email protected]], key];
key = strpadr[key, 2 b, "0"];
`hmac["what do ya want for nothing?", "Jefe", md5]`
`"750c783e6ab0b503eaa86e310a5db738"`