mldvx4 has asked for the wisdom of the Perl Monks concerning the following question:
I have some hexadecimal data, 8792ebfe26cc130030c20011c89f23c8, that should have a CRC16 value of 61624 aka 0xf0b8
How can I produce that result with Digest::CRC at all? The following code does not produce the expected CRC16 result:
#!/usr/bin/perl use strict; use warnings; use Digest::CRC; my $crc = qq(f0b8); print qq(target crc =$crc\n); my $msg = qq(8792ebfe26cc130030c20011c89f23c8); $msg = pack( 'H32', $msg ); my $ctx = Digest::CRC->new(width=>16, init=>0xffff, xorout=>0xffff, refout=>0, poly=>0x8408, refin=>1, cont=>1); $ctx->add($msg); my $crc2 = $ctx->hexdigest; print qq( crc = $crc2\n);
Where have I made the error(s) above?
I'm not a mathematician at all and I'm a long-time perl novice. The source to Digest::Perl is over my head. So I've also tried wrapping the above in several foreach loops to use combinations of xorout, refout, poly, and refin and both packed and unpacked, but to no avail.
In contrast, the following script appears to produce the expected result, at least according to the test-vectors.txt page. The below is based on yubikey_crc16 in ykcrc.c, but I would like to use Digest:CRC if that is possible.
#!/usr/bin/perl use strict; use warnings; # https://github.com/Yubico/yubico-c/blob/master/test-vectors.txt # https://github.com/Yubico/yubico-c/blob/master/ykcrc.c # (yubikey_crc16) my $plaintext = qq(8792ebfe26cc130030c20011c89f23c8); print qq(p=$plaintext\n); my $crc = &yubi_crc($plaintext, 16); print qq(yubi crc = ),$crc,qq( "),sprintf("0x%02x", $crc),qq("\n); print qq(target = 61624 "0xf0b8"\n); exit ( 0 ); sub yubi_crc { my ( $otp, $size ) = ( @_ ); my $crc = 0xffff; # while ( $size-- ) { my $byte = hex( substr( $otp, 0, 2, '' ) ); $crc = $crc ^ ( $byte & 0xff ); for ( my $i = 0; $i < 8; $i++) { my $n = $crc & 1; $crc = $crc >> 1; $crc = $crc ^ 0x8408 if ( $n != 0 ); } } return ( $crc ); }
Edit: Thanks. It was the polynomial which was off. Setting it to 0x1021 works. How did you know that was it? It seems to be part of the CRC-16-CCITT description. But why just that number?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using Digest::CRC to find CRC16 checksum
by Anonymous Monk on Jun 07, 2015 at 14:57 UTC | |
|
Re: Using Digest::CRC to find CRC16 checksum
by ww (Archbishop) on Jun 07, 2015 at 11:21 UTC |