1 |
#!/usr/bin/perl -w |
2 |
|
3 |
# guess-crc.pl |
4 |
# |
5 |
# 09/28/08 21:54:24 CEST Dobrica Pavlinusic <dpavlin@rot13.org> |
6 |
|
7 |
use strict; |
8 |
|
9 |
use Digest::CRC qw(crc32 crc16 crcccitt crc crc8); |
10 |
use Data::Dump qw/dump/; |
11 |
|
12 |
my $debug = 1 if @ARGV; |
13 |
|
14 |
sub hex2b { |
15 |
my $hex = shift; |
16 |
return map { hex($_) } split(/\s+/, $hex); |
17 |
} |
18 |
|
19 |
my @check_polys = ( 0x0000 .. 0xffff ); |
20 |
@check_polys = ( 32833, 43271, 32833, 43271, 19299, 35925, 47123, 49319, 56971 ); |
21 |
|
22 |
my @check_offset = ( 0,1,2,3 ); |
23 |
@check_offset = ( 1 ); # skip first, second always zero |
24 |
|
25 |
my $found_polys; |
26 |
|
27 |
sub check_crc { |
28 |
my ( $poly, $bytes, $wanted ) = @_; |
29 |
my $ctx = Digest::CRC->new( |
30 |
#width=>16, init=>0xffff, xorout=>0, refout=>1, poly=>0x1021, refin=>0 # ccitt |
31 |
#width=>16, init=>0, xorout=>0, refout=>1, poly=>0x8005, refin=>1 # crc16 |
32 |
#0x8408, |
33 |
#0xa001, |
34 |
width=>16, init=>0, xorout=>0, refout=>1, poly=>$poly,refin=>1 |
35 |
#width=>16, init=>0xffff, xorout=>0, refout=>1, poly=>$poly, refin=>0 # ccitt |
36 |
); |
37 |
$ctx->add( $bytes ); |
38 |
my $try = $ctx->digest; |
39 |
my $str = pack('n*', $try); |
40 |
warn "## check_crc( $poly, ",dump($bytes)," ) = ",dump( $str, $wanted ) if $debug; |
41 |
return $str eq $wanted; |
42 |
} |
43 |
|
44 |
foreach ( |
45 |
'D5 00 05 04 00 11 8C 66', |
46 |
'D6 00 05 FE 00 05 FA 40', |
47 |
) { |
48 |
my $hex = $_; |
49 |
$hex =~ s/\s+//g; |
50 |
|
51 |
my $bytes = pack('H*', substr($hex, 0, -4)); |
52 |
|
53 |
warn "?? guess crc ",substr($hex,-4); |
54 |
my $crc = pack('H4', substr($hex,-4)); |
55 |
|
56 |
warn "input $_ => ",dump( $bytes, $crc ); |
57 |
|
58 |
foreach my $o ( @check_offset ) { |
59 |
my $b = substr( $bytes, $o ); |
60 |
|
61 |
foreach my $poly ( @check_polys ) { |
62 |
|
63 |
print "## poly $poly\n" if $poly % 1000 == 0; |
64 |
|
65 |
if ( check_crc( $poly, $b, $crc ) ) { |
66 |
warn "HIT: $o poly: $poly\n"; |
67 |
$found_polys->{$poly}->{$o}++; |
68 |
} |
69 |
} |
70 |
} |
71 |
} |
72 |
|
73 |
print "FOUND polys = ", dump( $found_polys ); |