如何从Java中的byte []计算Internet校验和

时间:2010-11-06 16:06:22

标签: java checksum ip-protocol

我正在试图弄清楚如何计算Java中的Internet Checksum,这让我无法忍受痛苦。 (我对位操作很恐怖。)我在C#Calculate an Internet (aka IP, aka RFC791) checksum in C#中找到了一个版本。但是,我尝试将其转换为Java并不会产生正确的结果。谁能看到我做错了什么?我怀疑是数据类型问题。

public long getValue() {
    byte[] buf = { (byte) 0xed, 0x2A, 0x44, 0x10, 0x03, 0x30};
    int length = buf.length;
    int i = 0;

    long sum = 0;
    long data = 0;
    while (length > 1) {
        data = 0;
        data = (((buf[i]) << 8) | ((buf[i + 1]) & 0xFF));

        sum += data;
        if ((sum & 0xFFFF0000) > 0) {
            sum = sum & 0xFFFF;
            sum += 1;
        }

        i += 2;
        length -= 2;
    }

    if (length > 0) {
        sum += (buf[i] << 8);
        // sum += buffer[i];
        if ((sum & 0xFFFF0000) > 0) {
            sum = sum & 0xFFFF;
            sum += 1;
        }
    }
    sum = ~sum;
    sum = sum & 0xFFFF;
    return sum;
}

3 个答案:

答案 0 :(得分:17)

编辑以应用来自@ Andy,@ EJP,@ RD等人的评论并添加额外的测试用例以确保。

我使用了@Andys答案的组合(正确识别问题的位置)并更新了代码,以包括链接答案中提供的单元测试以及verified message checksum附加测试用例。

首先是实施

package org.example.checksum;

public class InternetChecksum {

  /**
   * Calculate the Internet Checksum of a buffer (RFC 1071 - http://www.faqs.org/rfcs/rfc1071.html)
   * Algorithm is
   * 1) apply a 16-bit 1's complement sum over all octets (adjacent 8-bit pairs [A,B], final odd length is [A,0])
   * 2) apply 1's complement to this final sum
   *
   * Notes:
   * 1's complement is bitwise NOT of positive value.
   * Ensure that any carry bits are added back to avoid off-by-one errors
   *
   *
   * @param buf The message
   * @return The checksum
   */
  public long calculateChecksum(byte[] buf) {
    int length = buf.length;
    int i = 0;

    long sum = 0;
    long data;

    // Handle all pairs
    while (length > 1) {
      // Corrected to include @Andy's edits and various comments on Stack Overflow
      data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF));
      sum += data;
      // 1's complement carry bit correction in 16-bits (detecting sign extension)
      if ((sum & 0xFFFF0000) > 0) {
        sum = sum & 0xFFFF;
        sum += 1;
      }

      i += 2;
      length -= 2;
    }

    // Handle remaining byte in odd length buffers
    if (length > 0) {
      // Corrected to include @Andy's edits and various comments on Stack Overflow
      sum += (buf[i] << 8 & 0xFF00);
      // 1's complement carry bit correction in 16-bits (detecting sign extension)
      if ((sum & 0xFFFF0000) > 0) {
        sum = sum & 0xFFFF;
        sum += 1;
      }
    }

    // Final 1's complement value correction to 16-bits
    sum = ~sum;
    sum = sum & 0xFFFF;
    return sum;

  }

}

然后在JUnit4中进行单元测试

package org.example.checksum;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class InternetChecksumTest {
  @Test
  public void simplestValidValue() {
    InternetChecksum testObject = new InternetChecksum();

    byte[] buf = new byte[1]; // should work for any-length array of zeros
    long expected = 0xFFFF;

    long actual = testObject.calculateChecksum(buf);

    assertEquals(expected, actual);
  }

  @Test
  public void validSingleByteExtreme() {
    InternetChecksum testObject = new InternetChecksum();

    byte[] buf = new byte[]{(byte) 0xFF};
    long expected = 0xFF;

    long actual = testObject.calculateChecksum(buf);

    assertEquals(expected, actual);
  }

  @Test
  public void validMultiByteExtrema() {
    InternetChecksum testObject = new InternetChecksum();

    byte[] buf = new byte[]{0x00, (byte) 0xFF};
    long expected = 0xFF00;

    long actual = testObject.calculateChecksum(buf);

    assertEquals(expected, actual);
  }

  @Test
  public void validExampleMessage() {
    InternetChecksum testObject = new InternetChecksum();

    // Berkley example http://www.cs.berkeley.edu/~kfall/EE122/lec06/tsld023.htm
    // e3 4f 23 96 44 27 99 f3
    byte[] buf = {(byte) 0xe3, 0x4f, 0x23, (byte) 0x96, 0x44, 0x27, (byte) 0x99, (byte) 0xf3};

    long expected = 0x1aff;

    long actual = testObject.calculateChecksum(buf);

    assertEquals(expected, actual);
  }

  @Test
  public void validExampleEvenMessageWithCarryFromRFC1071() {
    InternetChecksum testObject = new InternetChecksum();

    // RFC1071 example http://www.ietf.org/rfc/rfc1071.txt
    // 00 01 f2 03 f4 f5 f6 f7
    byte[] buf = {(byte) 0x00, 0x01, (byte) 0xf2, (byte) 0x03, (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7};

    long expected = 0x220d;

    long actual = testObject.calculateChecksum(buf);

    assertEquals(expected, actual);

  }

}

答案 1 :(得分:12)

更短的版本如下:

long checksum(byte[] buf, int length) {
    int i = 0;
    long sum = 0;
    while (length > 0) {
        sum += (buf[i++]&0xff) << 8;
        if ((--length)==0) break;
        sum += (buf[i++]&0xff);
        --length;
    }

    return (~((sum & 0xFFFF)+(sum >> 16)))&0xFFFF;
}

答案 2 :(得分:2)

我认为是造成麻烦的类型推广。让我们看看data = (((buf[i]) << 8) | ((buf[i + 1]) & 0xFF))

  1. ((buf[i]) << 8)会将buf[i]提升为int,从而导致签名扩展
  2. (buf[i + 1]) & 0xFF还会将buf[i + 1]提升为int,从而导致广告扩展。但是用0xff掩盖这个参数是正确的 - 在这种情况下我们得到正确的操作数。
  3. 整个表达式被提升为long(再次包含符号)。
  4. 问题出在第一个论点 - 它应该用0xff00掩盖,如:data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF))。但我怀疑为Java实现了更高效的算法,甚至标准库也有一个。您可以查看MessageDigest,也许它有一个。