Skip to content

Commit

Permalink
Merge pull request #204 from pongpet-licel/master
Browse files Browse the repository at this point in the history
Fixed CRC32 calculation to reflect input and result
  • Loading branch information
licel authored Mar 13, 2023
2 parents fa9d42e + f8113c1 commit b54b18b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
24 changes: 21 additions & 3 deletions src/main/java/com/licel/jcardsim/crypto/CRC32.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ private void crc32(byte inBuf[], short inOff, short inLen) {
short poly_l = Util.getShort(polynom, (short) 2);
byte carry = 0;
for (short i = inOff; i < (short) (inOff + inLen); i++) {
short d_h = (short) (inBuf[i] << 8);
short d_h = (short) (reflect8(inBuf[i]) << 8);
for (short k = 0; k < 8; k++) {
if (((fcs_h ^ d_h) & 0x8000) != 0) {
carry = 0;
Expand Down Expand Up @@ -104,8 +104,26 @@ private void crc32(byte inBuf[], short inOff, short inLen) {

}

Util.setShort(crc32, (short) 2, fcs_l);
Util.setShort(crc32, (short) 0, fcs_h);
Util.setShort(crc32, (short) 2, reflect16(fcs_h));
Util.setShort(crc32, (short) 0, reflect16(fcs_l));
}

private byte reflect8(byte input){
byte reflected = 0;
for( byte i = 0; i < 8; i++){
if((input & (0x80 >> i)) > 0 )
reflected |= (1 << i);
}
return reflected;
}

private short reflect16(short input){
short reflected = 0;
for( byte i = 0; i < 16; i++){
if((input & (0x8000 >> i)) > 0 )
reflected |= (1 << i);
}
return reflected;
}

short shift(short s) {
Expand Down
4 changes: 3 additions & 1 deletion src/test/java/com/licel/jcardsim/crypto/CRC32Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import junit.framework.TestCase;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
import java.util.zip.CRC32;

/**
* Test for <code>CRC32</code>
Expand All @@ -29,7 +30,8 @@ public class CRC32Test extends TestCase {
// etalon msg
String MESSAGE = "C46A3D01F5494013F9DFF3C5392C64";
// etalon crc
String CRC = "7C6277D0";
// String CRC = "7C6277D0";
String CRC = "C6A5A2E4";

public CRC32Test(String testName) {
super(testName);
Expand Down

0 comments on commit b54b18b

Please sign in to comment.