织梦CMS - 轻松建站从此开始!

罗索

计算PE文件校验和的C语言实现

落鹤生 发布于 2011-11-08 14:47 点击:次 
在某些时候可能你并不想用imagehlp!CheckSumMappedFile()去计算PE文件校验和,这个函数或许用得上。网上ASM实现很多,C实现不好找吧。最近因为要写个程序自动剁tcpip.sys,顺便折腾了一下PE文件校验和的计算。
TAG:

#if 0

http://www.sczgroup.org/windows/200701102106.txt

在某些时候可能你并不想用imagehlp!CheckSumMappedFile()去计算PE文件校验和,

这个函数或许用得上。网上ASM实现很多,C实现不好找吧。

最近因为要写个程序自动剁tcpip.sys,顺便折腾了一下PE文件校验和的计算。

#endif

/*

 * RFC 1141 : Incremental Updating of the Internet Checksum

 * 2007-01-10 21:06 scz

 * PE首部的CheckSum是4字节的DWORD型,计算方法与IP首部校验和非常类似,其C语

 * 言实现一直不太好找,这里给一个基于IP首部校验和C实现修改后的函数。已经处

 * 理了奇偶。形参base_sum为旧的CheckSum,无论原值是否正确,不必将内存中的

 * 该字段清零再计算,如果清零,则base_sum也要赋成零再计算。

 * 2007-01-29 15:30 scz

 * 更正了一个BUG,注意sum的数据类型是64-bits的。

 */

 

  1. static unsigned int pe_cksum 
  2.     unsigned short int *addr, 
  3.     unsigned int        len, 
  4.     unsigned long long  base_sum 
  5.     unsigned int        nleft   = len; 
  6.     /* 
  7.      * 这里不同,反码加一即取负,这种变态写法仅仅是为了避免一个编译警告。 
  8.      * 
  9.      * LONGLONG 
  10.      * ULONG64 
  11.      * unsigned long long 
  12.      */ 
  13.     unsigned long long  sum     = ~base_sum + 1; 
  14.     unsigned short int *w       = addr; 
  15.     unsigned short int  answer  = 0; 
  16.  
  17.     /* 
  18.      * Our algorithm is simple, using a 32 bit accumulator (sum), we add 
  19.      * sequential 16 bit words to it, and at the end, fold back all the 
  20.      * carry bits from the top 16 bits into the lower 16 bits. 
  21.      */ 
  22.     while ( nleft > 1 ) 
  23.     { 
  24.         sum    += *w++; 
  25.         nleft  -= 2; 
  26.     } 
  27.     /* 
  28.      * mop up an odd byte, if necessary 
  29.      */ 
  30.     if ( 1 == nleft ) 
  31.     { 
  32.         *( unsigned char * )( &answer )     = *( unsigned char * )w ; 
  33.         sum                                += answer; 
  34.     } 
  35.     /* 
  36.      * add back carry outs from top 16 bits to low 16 bits 
  37.      * 
  38.      * add hi 16 to low 16 
  39.      */ 
  40.     sum     = ( sum >> 16 ) + ( sum & 0xFFFF ); 
  41.     /* 
  42.      * add carry 
  43.      */ 
  44.     sum    += ( sum >> 16 ); 
  45.     /* 
  46.      * truncate to 16 bits 
  47.      */ 
  48.     answer  = ( unsigned short )( sum & 0xFFFF ); 
  49.     /* 
  50.      * 这里不同 
  51.      * 
  52.      * add len 
  53.      */ 
  54.     sum     = answer + len; 
  55.     return( ( unsigned int )sum ); 
  56. }  /* end of pe_cksum */ 
(scz)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201111/15289.html]
本文出处:hi.baidu.com/cr0_3 作者:scz
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
相关文章
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容