Skip to main content

binary - HMAC implementation in pure Mathematica


I am trying to implement the HMAC algorithm in Mathematica. The algorithm is a relatively simple way of signing messages with a key.


Here is some pseudocode from Wikipedia:


enter image description here


My attempt:


hash[string_String, method_String : "SHA256"] := FromCharacterCode @ 

Interpreter["HexInteger"] @ StringPartition[IntegerString[Hash[string, method], 16], 2];

HMAC[key_String, message_String, method_String : "SHA256", blockSize_Integer : 64] :=
Module[
{char54, char92, key2, ipad, opad},
{char54, char92} = FromCharacterCode /@ {54, 92};
key2 = Switch[StringLength @ key,
blockSize, key,
l_ /; l > blockSize, hash[key, method],
_, StringPadRight[key, blockSize, FromCharacterCode @ 0]];

ipad = FromCharacterCode[BitXor @@ Map[ToCharacterCode, {StringRepeat[char54, blockSize], key2}]];
opad = FromCharacterCode[BitXor @@ Map[ToCharacterCode, {StringRepeat[char92, blockSize], key2}]];
hash @ StringJoin[opad, hash @ StringJoin[ipad, message]]];

A Java analog for testing:


Needs["JLink`"];
LoadJavaClass["javax.crypto.Mac"];

javaHMAC[key_, message_] := Module[
{mac, keySpec, bytes},

JavaBlock[
mac = Mac`getInstance["HmacSHA256"];
keySpec = JavaNew["javax.crypto.spec.SecretKeySpec", ToCharacterCode[key], "HmacSHA256"];
mac @ init[keySpec];
bytes = mac @ doFinal[ToCharacterCode[message]] + 256;
FromCharacterCode @ bytes]];

In my particular case I am using this to communicate with Amazon Web Services. At the bottom of this page they provide a test vector which involves repeated HMAC computations. For these inputs (using outputs as the key for the next input)


key = "AWS4" <> "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
messages = {"20120215", "us-east-1", "iam", "aws4_request"};


we should obtain


"kSecret  = '41575334774a616c725855746e46454d492f4b374d44454e472b62507852666943594558414d504c454b4559'
kDate = '969fbb94feb542b71ede6f87fe4d5fa29c789342b0f407474670f0c2489e0a0d'
kRegion = '69daa0209cd9c5ff5c8ced464a696fd4252e981430b10e3d3fd8e2f197d7a70c'
kService = 'f72cfd46f26bc4643f06a11eabb6c0ba18780c19a8da0c31ace671265e3c87fa'
kSigning = 'f4780e2d9f65fa895f9c67b32ce1baf0b0d8a43505a000a1a9e090d414db404d'";
StringSplit[StringSplit[%, "\n"], "= "][[All, 2]];
correct = StringReplace[%, "'" -> ""];


My function passes this test. Swapping it out for the Java method will show that the same results are obtained.


FoldList[HMAC, key, messages];
StringJoin /@ IntegerString[ToCharacterCode @ %, 16, 2];
MapThread[SequenceAlignment, {%, correct}];
% // Column


{41575334774a616c725855746e46454d492f4b374d44454e472b62507852666943594558414d504c454b4559}


{969fbb94feb542b71ede6f87fe4d5fa29c789342b0f407474670f0c2489e0a0d}


{69daa0209cd9c5ff5c8ced464a696fd4252e981430b10e3d3fd8e2f197d7a70c}



{f72cfd46f26bc4643f06a11eabb6c0ba18780c19a8da0c31ace671265e3c87fa}


{f4780e2d9f65fa895f9c67b32ce1baf0b0d8a43505a000a1a9e090d414db404d}



But on a slightly different set of messages, from the bottom of this page, my function fails on one of the steps.


messages2 = {"20110909", "us-east-1", "iam", "aws4_request"};

FoldList[HMAC, key, messages2];
hex2 = StringJoin /@ IntegerString[ToCharacterCode @ %, 16, 2];

FoldList[javaHMAC, key, messages2];

javaHex2 = StringJoin /@ IntegerString[ToCharacterCode @ %, 16, 2];

MapThread[SequenceAlignment, {hex2, javaHex2}] // Column


{41575334774a616c725855746e46454d492f4b374d44454e472b62507852666943594558414d504c454b4559}


{a83ed188be5f4b074d7f66349f5077fbcdf797bf3471fb9d5f32730f936d41a5}


{957b5875f33834a85374b750011dc2d6f0e1d6896eeb891d36a73c711961ad6e}


{{,0},116249d060bff83faa1a627e85a4c6f83ce50d89c334765878dcf76e28bfc6,{,e}}


{{a4b,98f1},d,{,889f},e,{1,c},4,{b2f,f44},21,{2,adc},5,{8145,22b},a,{,b0ce1},f,{6,},8,{1,2e6},9,{d7,29},c,{4e4,262},e,{17a88,d},1,{31,5e},5a9,{f85,4c9},0,{33,ef},d,{b,},1,{d858,},e,{6,},3,{f52,b0e},7,{51,}}




In this case the Java output matches the answer provided by AWS.


I cannot get this implementation to work either.



Answer



Try something like


hash[string_String, method_String: "SHA256"] :=
FromCharacterCode@IntegerDigits[Hash[string, method], 256, 32]

The original method you used will drop leading zeros. You can even see that in your example data set:


{{,0},116249d060bff83faa1a627e85a4c6f83ce50d89c334765878dcf76e28bfc6,{,e}}


ETA: I should have mentioned that passing in the algorithm but then hard-coding the length of the expected hash to 32 bytes is extremely sloppy of me. Do not do that in production code.


Comments

Popular posts from this blog

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1....