我利用过的一些校验函数
sha1:
openssl提供了sha1的库,在安装openssl之后可以直接挪用sha1。
MD5:
函数原型见附件,个中static void MDFile (filename)是对文件举办MD5校验的,static void MDString (inString)是对字符串举办MD5校验的。可以直接利用,也可以封装成库后在挪用,值得留意的是,需要将源码中函数界说中的static去掉。
hash:
hash算法见附件。
TCP/IP/UDP/ICMP中的checksum:
/*计较校验和*/
USHORT checksum(USHORT *buffer,int size)
{
unsigned long cksum=0;
while(size>1)
{
cksum+=*buffer++;
size -=sizeof(USHORT);
}
if(size)
{
cksum+=*(UCHAR*)buffer;
}
cksum =(cksum>>16)+(cksum & 0xffff);
cksum+=(cksum>>16);
return (USHORT)(~cksum);
}
CRC校验:
int file_crc32(const char *filename,unsigned int *crc)
{
unsigned char buffer[MAX_BUFFER_SIZE];
unsigned int vcrc = 0xffffffff;
unsigned int read = 0;
unsigned int filesize = 0;
FILE *fp = NULL;
struct stat fst;
if(stat(filename,&fst))
{
printf("get file info failed\n");
return -1;
}
/* unsigned long may denote the file size */
if((filesize = fst.st_size) == 0)
return -1;
/* open file */
if((fp = fopen(filename,"r")) == NULL)
{
printf("open the file failed\n");
}
while(filesize)
{
read = filesize > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE:filesize;
if((read = fread(buffer,1,read,fp)) == 0) break;
/* CRC */
crc32(buffer,read,&vcrc);
filesize -= read;
}
*crc = ~vcrc;
fclose(fp);
return 0;
}
void crc32(const unsigned char* byte,unsigned int length,unsigned int *vcrc)
{
unsigned int i = 0;
for(i = 0; i < length; i++)
*vcrc = ((*vcrc) >> 8) ^ crc32table[byte[i] ^ ((*vcrc) & 0x000000FF)];
}
文章来历:http://qq164587043.blog.51cto.com/261469/159169