Hello,
I am trying to create a CMAC out of some JSON data (I have a reason for
doing this -- part of the authorization allowing my REST client to
communicate with a server that requires it). I figured I would use
Digest::CMAC to do this (but if someone knows a better way, please let me
know). However, I'm trying to create the CMAC out of JSON data, and I'm
getting an error. I wrote a little test script to demonstrate, here's the
code:
<CODE>
#!/export/home/apps/public/bin/perl
use strict;
use warnings;
use JSON;
use Digest::CMAC;
my $key = '1737567790727776';
my $data = {
one => 1,
two => 2,
three => 3,
four => 4,
five => 5,
};
# prefix null values to make the number of bytes a multiple of 16 to make
Digest::CMAC happy
sub formatTo16 {
my $string = shift;
my $result = "\0" x (16 - length($string)%16) . $string;
return $result;
};
my $omac1 = Digest::CMAC->new($key);
my $json = JSON::to_json($data);
print "\$json is: $json\nAttempting to Digest::CMAC->add(\$json)\n";
eval { $omac1->add(&formatTo16($json)); };
warn "[eval error]: $@" if $@;
# my $binary_tag = $omac1->digest;
# print $binary_tag, "\n";
print '-'x80, "\n";
my $cipher = Crypt::Rijndael->new($key, Crypt::Rijndael::MODE_CBC() );
my $crypted = $cipher->encrypt(&formatTo16($json));
print 'Crypt::Rijndael->encrypt(\$json): ', $crypted, "\n";
</CODE>
I added the Crypt::Rijndael->encrypt at the end just to see if that would
work on the bare JSON string, and it does. Here's the output of the script:
<OUTPUT>
$json is: {"three":3,"five":5,"one":1,"two":2,"four":4}
Attempting to Digest::CMAC->add($json)
[eval error]: encrypt: datasize not multiple of blocksize (16 bytes) at
/export/home/apps/public/lib/perl5/site_perl/5.10.0/Digest/OMAC/Base.pm
line 56.
--------------------------------------------------------------------------------
Crypt::Rijndael->encrypt(\$json): G`'/Mβ©Y¦¾Ï)=ôÎlÛÝf?´²lÕeyûÊ¡í
</OUTPUT>
If not for the eval, the script would stop execution at that error.
The Crypt::Rijndael->encrypt call on the bare JSON does not cause an error.
Does anyone have a suggestion for how I can create a CMAC using a JSON
string?
Thanks,
John