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)];
}