您的位置:首页 > 其它

我使用过的一些校验函数

2009-05-19 00:40 357 查看
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)];
}本文出自 “国产0与1” 博客,请务必保留此出处http://qq164587043.blog.51cto.com/261469/159169
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: