阅读 93

plc(Power Line Communication)通信测试程序

plc(Power Line Communication)通信测试程序 plconfig.c

/*
	plconfig.c version 0.2
	Source code for Intellon-based Powerline bridge configuration tool

	Copyright (C) 2002-2003 Manuel Kasper <mk@neon1.net>.
	All rights reserved.
*/

/*
 * 	Linux specific code by Enrik Berkhan <enrik.berkhan@inka.de>
 * 	Copyright (C) 2004 Manuel Kasper <mk@neon1.net>.
 */

#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>

#ifdef LINUX
#include <linux/types.h>
#include <netinet/in.h>
#include <netpacket/packet.h>
#include <net/ethernet.h>
#include <string.h>
#include <signal.h>
#else
#include <net/bpf.h>
#endif

#include <sys/socket.h>
#include <net/if.h>
#include <stdio.h>
#include <sys/uio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "global.h"
#include "md5.h"

#define PLCONFIG_VERSION "0.2"
#define ETHERTYPE_INTELLON	0x88E1

#define logictostr(x) (x) ? "yes" : "no"

#ifndef LINUX
/* bpf instructions to filter for Intellon ethertype packets */
struct bpf_insn insns[] = {
	 BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
	 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ETHERTYPE_INTELLON, 0, 1),
	 BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
	 BPF_STMT(BPF_RET+BPF_K, 0)
};
#endif

u_short ex_word(u_char *ptr) {
	return ntohs(*((u_short*)ptr));
}

u_long ex_long(u_char *ptr) {
	return ntohl(*((u_long*)ptr));
}

char *format_mac_addr(u_char *addr, char *macbuf) {
	
	sprintf(macbuf, "%02x:%02x:%02x:%02x:%02x:%02x",
		addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
		
	return macbuf;
}

void dump_params_and_stats(u_char *macmgmt) {
	
	printf("  Tx ACK Counter:             %u\n"
	       "  Tx NACK Counter:            %u\n"
	       "  Tx FAIL Counter:            %u\n"
	       "  Tx Contention Loss Counter: %u\n"
	       "  Tx Collision Counter:       %u\n"
	       "  Tx CA3 Latency Counter:     %u\n"
	       "  Tx CA2 Latency Counter:     %u\n"
	       "  Tx CA1 Latency Counter:     %u\n"
	       "  Tx CA0 Latency Counter:     %u\n"
	       "  Rx Cumul. Bytes per 40-symbol Packet Counter: %lu\n",
	       
	       ex_word(&macmgmt[2]), ex_word(&macmgmt[4]), ex_word(&macmgmt[6]),
	       ex_word(&macmgmt[8]), ex_word(&macmgmt[10]), ex_word(&macmgmt[12]),
	       ex_word(&macmgmt[14]), ex_word(&macmgmt[16]), ex_word(&macmgmt[18]),
	       ex_long(&macmgmt[20]));
}

void dump_network_statistics(u_char *macmgmt) {
	
	int		da;
	u_char	*stat;
	char	macbuf[20];
	
	for (da = 0; da < 15; da++) {
		
		stat = (macmgmt+9+da*12);
		
		/* Check to see if that node entry is valid -
		   stupid Intellon chip is supposed to return 00:00:00:00:00:00 for
		   nonexistant nodes (as per the specs), but instead it returns
		   01:00:00:00:00:00 so we just skip checking the first byte,
		   since heaven knows what else it may return instead of 01 in
		   other places/revisions.
		*/
		
		if (!((stat[1] == 0) && (stat[2] == 0) &&
			  (stat[3] == 0) && (stat[4] == 0) && (stat[5] == 0))) {
			  
			printf("\n  Statistics for Network DA #%d:\n"
				   "  MAC address:         %s\n"
				   "  Bytes in 40 symbols: %u\n"
				   "  FAILS received:      %u\n"
				   "  Frame Drops:         %u\n",
				   
				   da+1, format_mac_addr(stat, macbuf), ex_word(&stat[6]),
				   ex_word(&stat[8]), ex_word(&stat[10])); 
		}
	}
}

void dump_tx_characteristics(u_char *macmgmt) {

	char *retrtab[] = {"Transmit without retries",
		"Transmit with one retry only",
		"Transmit with normal retries (HomePlug)", "Reserved"};
	
	printf("  Local consumption only:        %s\n"
		   "  Encryption flag:               %s\n"
		   "  Transmit priority:             %u\n"
		   "  Response expected:             %s\n"
		   "  Transmit contention free:      %s\n"
		   "  Retry control:                 %s\n"
		   "  No default encryption receive: %s\n"
		   "  No unencrypted receive:        %s\n"
		   "  Transmit EKS:                  %u\n",
		   
		   logictostr(macmgmt[2] & 0x80), logictostr(macmgmt[2] & 0x40),
		   (macmgmt[2] >> 4) & 0x03, logictostr(macmgmt[2] & 0x08), 
		   logictostr(macmgmt[2] & 0x04), retrtab[(macmgmt[3] >> 6) & 0x03],
		   logictostr(macmgmt[3] & 0x08), logictostr(macmgmt[3] & 0x04),
		   macmgmt[4]);
}

void dump_set_key(u_char *macmgmt) {

	char	asckey[17];
	char	*hextab = "0123456789abcdef";
	int		i;
	
	/* Convert the key to ASCII hex */
	for (i = 0; i < 8; i++) {
		asckey[i<<1] = hextab[(macmgmt[i+3] >> 4) & 0x0F];
		asckey[(i<<1)+1] = hextab[macmgmt[i+3] & 0x0F];
	}
	
	asckey[16] = 0;
	
	printf("  Encryption key select:  0x%02x\n"
	       "  Network encryption key: %s\n",
	       
	       macmgmt[2], asckey); 
	       
}

void read_display_responses(int netfd, u_char *framebuf, u_int buflen) {

	u_char	*frameptr;
	ssize_t rdlen;
	u_int	i, j;
#ifdef LINUX
	struct sockaddr_ll addr;
	socklen_t addrlen = sizeof(addr);
#else
	struct bpf_hdr *header;
#endif
	char macbuf[20];

	/* read responses */
	while (1) {
#ifdef LINUX
		rdlen = recvfrom(netfd, framebuf+ETHER_HDR_LEN, buflen-ETHER_HDR_LEN, MSG_TRUNC, (struct sockaddr *)&addr, &addrlen);
#else
		rdlen = read(netfd, framebuf, buflen);
#endif
		
		if (rdlen != -1) {
		
#ifdef LINUX
			if (rdlen > buflen-ETHER_HDR_LEN) {
				fprintf(stderr, "received jumbo frame of %d bytes len, truncated\n", rdlen);
			}
			frameptr = framebuf;
			memcpy(framebuf+6, &addr.sll_addr, 6);

			if (addr.sll_pkttype != PACKET_OUTGOING &&
			    addr.sll_protocol == htons(ETHERTYPE_INTELLON)) {
#else
			header = (struct bpf_hdr*)framebuf;
			frameptr = framebuf + header->bh_hdrlen;
			
			if ((frameptr[12] == 0x88) && (frameptr[13] == 0x7B)) {
#endif
			
				/* It's an intellon packet - read MAC management entries */
				j = 15;
				
				for (i = 0; i < (frameptr[14] & (u_int)0x7F); i++) {
					switch (frameptr[j]) {
					
						case 0x04:		/* Set Network Encryption Key */
							printf("\n- Set Network Encryption Key from %s\n",
								format_mac_addr(&frameptr[6], macbuf));
								
							dump_set_key(&frameptr[j]);
							break;
					
						case 0x07:		/* Request Parameters and Statistics */
							printf("\n- Parameters and Statistics request from %s\n",
								format_mac_addr(&frameptr[6], macbuf));
							break;
					
						case 0x08:		/* Parameters and Statistics Response */
							printf("\n- Parameters and Statistics response from %s\n",
								format_mac_addr(&frameptr[6], macbuf));
								
							dump_params_and_stats(&frameptr[j]);
							break;
							
						case 0x06:		/* Confirm Network Encryption Key */
							printf("\n- Network encryption key confirmation from %s\n",
								format_mac_addr(&frameptr[6], macbuf));
							break;
							
						case 0x1a:		/* Intellon specific network statistics */
							if (!(frameptr[j+2] & 0x80)) 	{	/* Really a response? */
								printf("\n- Intellon-specific network statistics from %s\n",
									format_mac_addr(&frameptr[6], macbuf));
								
								dump_network_statistics(&frameptr[j]);
							} else {
								printf("\n- Intellon-specific network statistics  request from %s\n",
								       format_mac_addr(&frameptr[6], macbuf));
							}
							break;
							
						case 0x1f:		/* Set transmit characteristics */
							printf("\n- Set transmit characteristics from %s\n",
								format_mac_addr(&frameptr[6], macbuf));
								
							dump_tx_characteristics(&frameptr[j]);							
							break;
							
							
						default:
							printf("- Unknown response (MTYPE = 0x%02x) from %s\n",
								frameptr[j], format_mac_addr(&frameptr[6], macbuf));
					}
					j += frameptr[j+1] + 2;
				}
			}
		}
	}
}

unsigned char deskeyparity(unsigned char kb) {
	unsigned char parity = 0, i, mykb = kb;
	
	for (i = 0; i < 7; i++) {
		mykb >>= 1;
		parity += (mykb & 0x01);
	}
	
	return ((kb & 0xFE) | (~parity & 0x01));
}

void usage(void) {
	
	printf("%s",
	       "\nPowerline Bridge config version " PLCONFIG_VERSION " by Manuel Kasper <mk@neon1.net>\n\n"
#ifdef LINUX
	       "Usage:   plconfig [-pqrh] [-s key] interface\n\n"
#else
	       "Usage:   plconfig [-pqrh] [-b device] [-s key] interface\n\n"
#endif
	
		   "         -s key            set network encryption key\n"
		   "                           (plaintext password or 8 hex bytes preceded by 0x)\n"
#ifndef LINUX
		   "         -b device         use device (default is /dev/bpf0)\n"
#endif
		   "         -p                don't switch interface to promiscuous mode\n"
		   "         -r                request parameters and statistics\n"
		   "         -q                request Intellon-specific network statistics\n"
		   "         -h                display this help\n\n"
		   
		   "         If -s is not specified, plconfig will listen for management packets\n"
		   "         indefinitely (after requesting stats if -r is specified)\n\n");
}

int main(int argc, char *argv[]) {
	int netfd, ch;
#ifdef LINUX
	struct sockaddr_ll addr = { 0,0,0,0,0,0,{0,} };
#else
	struct bpf_program filter;
#endif
	struct ifreq ifr;
	u_int buflen, i;
	u_char *framebuf;
#ifndef LINUX
	char ifname[8], bpfn[32] = "/dev/bpf0";
#endif
	u_char netkey[8], nib, outframe[200];
	
	/* options */
	int nopromisc = 0, mode = 0;
		
	/* Parse command line options */
	while ((ch = getopt(argc, argv, "s:b:pqrh")) != -1) {
	 
		 switch (ch) {
		 
			 case 'p':
				nopromisc = 1;
				break;
				
			 case 'r':
				mode = 1;
				break;
				
			 case 'q':
				mode = 3;
				break;
				
			 case 's':
				mode = 2;
				
				/* See if it begins with 0x */
				if ((optarg[0] == '0') && (optarg[1] == 'x')) {
								
					for (i = 0; i < 8; i++)
						netkey[i] = 0;
					
					/* convert ASCII hex to binary */
					for (i = 0; i < 16; i++) {
						if ((optarg[i+2] >= '0') && (optarg[i+2] <= '9')) {
							nib = optarg[i+2] - '0';
						} else if ((optarg[i+2] >= 'a') && (optarg[i+2] <= 'f')) {
							nib = optarg[i+2] + 0x0a - 'a';
						} else if ((optarg[i+2] >= 'A') && (optarg[i+2] <= 'F')) {
							nib = optarg[i+2] + 0x0a - 'A';
						} else {
							fprintf(stderr, "Unrecognized character '%c' in key\n", optarg[i+2]);
							exit(1);
						}
						
						if (i & 0x01)
							netkey[i >> 1] |= nib;
						else
							netkey[i >> 1] |= (nib << 4);
					}
				} else {
					/* It's a plaintext password - use PBKDF1 on it */
					MD5_CTX	md5ctx;
					u_char	digest[16], tmp[256];
					
					strncpy(tmp, optarg, 240);
					/* add salt */
					strcat(tmp, "\x08\x85\x6d\xaf\x7c\xf5\x81\x85");
					
					/* generate initial digest */
					MD5Init(&md5ctx);
					MD5Update(&md5ctx, tmp, strlen(tmp));
					MD5Final(digest, &md5ctx);
					
					/* loop 999 times as required by HomePlug */
					for (i = 0; i < 999; i++) {
						MD5Init(&md5ctx);
						MD5Update(&md5ctx, digest, 16);
						MD5Final(digest, &md5ctx);
					}
					
					/*	extract the first 8 bytes; calculate parity bit
						(LSB = odd parity), even though most powerline bridges
						seem to ignore it
					*/
					for (i = 0; i < 8; i++)
						netkey[i] = deskeyparity(digest[i]);
				}
				break;
				
#ifndef LINUX
			 case 'b':
				strncpy(bpfn, optarg, 32);
				break;
#endif
				
			 case '?':
			 case 'h':
			 default:
				usage();
				exit(0);
		 }
	}
	
	argc -= optind;
    argv += optind;
	
	if (argc != 1) {
		usage();
		exit(0);
	}
	
#ifndef LINUX
	strncpy(ifname, argv[0], 8);
#endif
	
	/* Open bpf device */
#ifdef LINUX
	netfd = socket(PF_PACKET, SOCK_DGRAM, htons(ETHERTYPE_INTELLON));
	if (netfd == -1) {
		perror("socket");
		exit(0);
	}
#else
	netfd = open(bpfn, O_RDWR);
	if (netfd == -1) {
		fprintf(stderr, "Cannot open %s\n", bpfn);
		exit(0);
	}
#endif
	
#ifdef LINUX
	strncpy(ifr.ifr_name, argv[0], sizeof(ifr.ifr_name));
	if (ioctl(netfd, SIOCGIFMTU, &ifr) == -1) {
		perror("ioctl(SIOCGIFMTU)");
		return(1);
	}
	buflen = ifr.ifr_mtu + ETHER_HDR_LEN;
#else
	/* Read buffer length */
	if (ioctl(netfd, BIOCGBLEN, &buflen) == -1) {
		fprintf(stderr, "ioctl(BIOCGBLEN) error!\n");
		exit(0);
	}
#endif
	
	/* Allocate buffer */
	if (!(framebuf = (u_char*)malloc((size_t)buflen))) {
		fprintf(stderr, "Cannot malloc() packet buffer!\n");
		exit(0);
	}
	
	/* Bind to interface */
#ifdef LINUX
	if (ioctl(netfd, SIOCGIFINDEX, &ifr) == -1) {
		perror("ioctl(SIOCGIFINDEX)");
		return(1);
	}
	addr.sll_family = AF_PACKET;
	addr.sll_protocol = htons(ETHERTYPE_INTELLON);
	addr.sll_ifindex = ifr.ifr_ifindex;
	if (bind(netfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
		perror("bind");
		return(1);
	}
#else
	strcpy(ifr.ifr_name, ifname);
	
	if (ioctl(netfd, BIOCSETIF, &ifr) == -1) {
		fprintf(stderr, "ioctl(BIOCSETIF) error!\n");
		exit(0);
	}
#endif

#ifndef LINUX
	/* Set filter */
	filter.bf_len = sizeof(insns) / sizeof(insns[0]);
	filter.bf_insns = insns;

	if (ioctl(netfd, BIOCSETF, &filter) == -1) {
		fprintf(stderr, "ioctl(BIOCSETF) error!\n");
		exit(0);
	}

	/* Set immediate mode */
	i = 1;	
	if (ioctl(netfd, BIOCIMMEDIATE, &i) == -1) {
		fprintf(stderr, "ioctl(BIOCIMMEDIATE) error!\n");
		exit(0);
	}
#endif
	
	/* Set promiscuous mode
	   This is necessary because the bridges seem to be returning
	   responses with the destination MAC address set to their own
	   MAC address instead of using broadcasts.
	*/
	if ((!nopromisc) && (mode != 2)) {
#ifdef LINUX
		struct packet_mreq mreq = { ifr.ifr_ifindex, PACKET_MR_PROMISC, 0, {0, }};
		if (setsockopt(netfd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) == -1) {
			perror("setsockopt(PACKET_ADD_MEMBERSHIP, PROMISC)");
			return 1;
		}
#else
		i = 1;	
		if (ioctl(netfd, BIOCPROMISC, &i) == -1) {
			fprintf(stderr, "ioctl(BIOCPROMISC) error!\n");
			exit(0);
		}
#endif
	}
	
#ifndef LINUX
	/* We don't want to see local packets */	
	i = 0;	
	if (ioctl(netfd, BIOCGSEESENT, &i) == -1) {
		fprintf(stderr, "ioctl(BIOCGSEESENT) error!\n");
		exit(0);
	}
#endif
	
	if (mode) {
#ifdef LINUX
		addr.sll_family = AF_PACKET;
		addr.sll_protocol = htons(ETHERTYPE_INTELLON);
		addr.sll_ifindex = ifr.ifr_ifindex;
		addr.sll_halen = 6;
		for (i = 0; i < 6; i++)
			addr.sll_addr[i] = 0xFF;        /* broadcast */
		outframe[0] =0x01;    /* one MAC management entry */
#else
		/* set up outgoing command frame */
		for (i = 0; i < 6; i++)
			outframe[i] = 0xFF;		/* broadcast */
			
		for (i = 0; i < 6; i++)
			outframe[i+6] = 0x00;	/* the source address will be set automatically */
			
		outframe[12] = 0x88;	/* Intellon ethertype */
		outframe[13] = 0x7b;
		
		outframe[14] = 0x01;	/* one MAC management entry */
#endif
	}
	
	switch (mode) {
	
		case 1:		/* request parameters & statistics */
#ifdef LINUX
			outframe[1] = 0x07;	/* request parameters and statistics */
			outframe[2] = 0x0;	    /* 0 bytes follow */
			
			/* write out packet */
			sendto(netfd, outframe, 3, 0, (struct sockaddr *)&addr, sizeof(addr));
#else
			outframe[15] = 0x07;	/* request parameters and statistics */
			outframe[16] = 0x0;	    /* 0 bytes follow */
			
			/* fill the rest with zeroes to maintain minimum data payload of 46 bytes */
			for (i = 0; i < 43; i++)
				outframe[i+17] = 0x00;
		
			/* write out packet */
			write(netfd, outframe, 60);
#endif
			break;
			
		case 2:		/* set network key */
#ifdef LINUX
			outframe[1] = 0x04;	/* set network key */
			outframe[2] = 0x09;	/* 9 bytes follow */
			outframe[3] = 0x01;	/* encryption key select -> 1 */
			
			for (i = 0; i < 8; i++)
				outframe[i+4] = netkey[i];

			/* write out packet */
			sendto(netfd, outframe, 12, 0, (struct sockaddr *)&addr, sizeof(addr));
#else
			outframe[15] = 0x04;	/* set network key */
			outframe[16] = 0x09;	/* 9 bytes follow */
			outframe[17] = 0x01;	/* encryption key select -> 1 */
			
			for (i = 0; i < 8; i++)
				outframe[i+18] = netkey[i];
				
			/* fill the rest with zeroes to maintain minimum data payload of 46 bytes */
			for (i = 0; i < 34; i++)
				outframe[i+26] = 0x00;
		
			/* write out packet */
			write(netfd, outframe, 60);
#endif
			break;
			
		case 3:		/* request Intellon-specific network statistics */
#ifdef LINUX
			outframe[1] = 0x1a;	/* request network statistics */
			outframe[2] = 0xbb;	/* 187 bytes follow */
			
			outframe[3] = 0x80;	/* read the stats, don't clear them */
			
			for (i = 0; i < 186; i++)
				outframe[i+4] = 0x00;
		
			/* write out packet */
			sendto(netfd, outframe, 190, 0, (struct sockaddr *)&addr, sizeof(addr));
#else
			outframe[15] = 0x1a;	/* request network statistics */
			outframe[16] = 0xbb;	/* 187 bytes follow */
			
			outframe[17] = 0x80;	/* read the stats, don't clear them */
			
			for (i = 0; i < 186; i++)
				outframe[i+18] = 0x00;
		
			/* write out packet */
			write(netfd, outframe, 204);
#endif
			break;
	}
	
	if (mode != 2)
		read_display_responses(netfd, framebuf, buflen);
	
	free(framebuf);
	
	/* Close bpf device */
	close(netfd);
	return 0;
}
复制代码

头文件:

/* GLOBAL.H - RSAREF types and constants
 */
/* PROTOTYPES should be set to one if and only if the compiler supports
  function argument prototyping.
  The following makes PROTOTYPES default to 0 if it has not already
  been defined with C compiler flags.
 */
#ifndef PROTOTYPES
#define PROTOTYPES 0
#endif

/* POINTER defines a generic pointer type */
typedef unsigned char *POINTER;

/* UINT2 defines a two byte word */
typedef unsigned short int UINT2;

/* UINT4 defines a four byte word */
typedef unsigned long int UINT4;

/* PROTO_LIST is defined depending on how PROTOTYPES is defined above.
If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it
  returns an empty list.
 */
#if PROTOTYPES
#define PROTO_LIST(list) list
#else
#define PROTO_LIST(list) ()
#endif
复制代码

md5:

/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
 */

#include "global.h"
#include "md5.h"

/* Constants for MD5Transform routine.
 */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21

static void MD5Transform PROTO_LIST ((UINT4 [4], unsigned char [64]));
static void Encode PROTO_LIST
  ((unsigned char *, UINT4 *, unsigned int));
static void Decode PROTO_LIST
  ((UINT4 *, unsigned char *, unsigned int));
static void MD5_memcpy PROTO_LIST ((POINTER, POINTER, unsigned int));
static void MD5_memset PROTO_LIST ((POINTER, int, unsigned int));

static unsigned char PADDING[64] = {
  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

/* F, G, H and I are basic MD5 functions.
 */
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))

/* ROTATE_LEFT rotates x left n bits.
 */
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))

/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
 */
#define FF(a, b, c, d, x, s, ac) { \
 (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }
#define GG(a, b, c, d, x, s, ac) { \
 (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }
#define HH(a, b, c, d, x, s, ac) { \
 (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }
#define II(a, b, c, d, x, s, ac) { \
 (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
 (a) = ROTATE_LEFT ((a), (s)); \
 (a) += (b); \
  }

/* MD5 initialization. Begins an MD5 operation, writing a new context.
 */
void MD5Init (context)
MD5_CTX *context;                                        /* context */
{
  context->count[0] = context->count[1] = 0;
  /* Load magic initialization constants.
*/
  context->state[0] = 0x67452301;
  context->state[1] = 0xefcdab89;
  context->state[2] = 0x98badcfe;
  context->state[3] = 0x10325476;
}

/* MD5 block update operation. Continues an MD5 message-digest
  operation, processing another message block, and updating the
  context.
 */
void MD5Update (context, input, inputLen)
MD5_CTX *context;                                        /* context */
unsigned char *input;                                /* input block */
unsigned int inputLen;                     /* length of input block */
{
  unsigned int i, index, partLen;

  /* Compute number of bytes mod 64 */
  index = (unsigned int)((context->count[0] >> 3) & 0x3F);

  /* Update number of bits */
  if ((context->count[0] += ((UINT4)inputLen << 3))
   < ((UINT4)inputLen << 3))
 context->count[1]++;
  context->count[1] += ((UINT4)inputLen >> 29);

  partLen = 64 - index;

  /* Transform as many times as possible.
*/
  if (inputLen >= partLen) {
 MD5_memcpy
   ((POINTER)&context->buffer[index], (POINTER)input, partLen);
 MD5Transform (context->state, context->buffer);

 for (i = partLen; i + 63 < inputLen; i += 64)
   MD5Transform (context->state, &input[i]);

 index = 0;
  }
  else
 i = 0;

  /* Buffer remaining input */
  MD5_memcpy
 ((POINTER)&context->buffer[index], (POINTER)&input[i],
  inputLen-i);
}

/* MD5 finalization. Ends an MD5 message-digest operation, writing the
  the message digest and zeroizing the context.
 */
void MD5Final (digest, context)
unsigned char digest[16];                         /* message digest */
MD5_CTX *context;                                       /* context */
{
  unsigned char bits[8];
  unsigned int index, padLen;

  /* Save number of bits */
  Encode (bits, context->count, 8);

  /* Pad out to 56 mod 64.
*/
  index = (unsigned int)((context->count[0] >> 3) & 0x3f);
  padLen = (index < 56) ? (56 - index) : (120 - index);
  MD5Update (context, PADDING, padLen);

  /* Append length (before padding) */
  MD5Update (context, bits, 8);

  /* Store state in digest */
  Encode (digest, context->state, 16);

  /* Zeroize sensitive information.
*/
  MD5_memset ((POINTER)context, 0, sizeof (*context));
}

/* MD5 basic transformation. Transforms state based on block.
 */
static void MD5Transform (state, block)
UINT4 state[4];
unsigned char block[64];
{
  UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];

  Decode (x, block, 64);

  /* Round 1 */
  FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */

 /* Round 2 */
  GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
  GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */

  /* Round 3 */
  HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
  HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */

  /* Round 4 */
  II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */

  state[0] += a;
  state[1] += b;
  state[2] += c;
  state[3] += d;

  /* Zeroize sensitive information.
*/
  MD5_memset ((POINTER)x, 0, sizeof (x));
}

/* Encodes input (UINT4) into output (unsigned char). Assumes len is
  a multiple of 4.
 */
static void Encode (output, input, len)
unsigned char *output;
UINT4 *input;
unsigned int len;
{
  unsigned int i, j;

  for (i = 0, j = 0; j < len; i++, j += 4) {
 output[j] = (unsigned char)(input[i] & 0xff);
 output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
 output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
 output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
  }
}

/* Decodes input (unsigned char) into output (UINT4). Assumes len is
  a multiple of 4.
 */
static void Decode (output, input, len)
UINT4 *output;
unsigned char *input;
unsigned int len;
{
  unsigned int i, j;

  for (i = 0, j = 0; j < len; i++, j += 4)
 output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
   (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
}

/* Note: Replace "for loop" with standard memcpy if possible.
 */

static void MD5_memcpy (output, input, len)
POINTER output;
POINTER input;
unsigned int len;
{
  unsigned int i;

  for (i = 0; i < len; i++)
    output[i] = input[i];
}

/* Note: Replace "for loop" with standard memset if possible.
 */
static void MD5_memset (output, value, len)
POINTER output;
int value;
unsigned int len;
{
  unsigned int i;

  for (i = 0; i < len; i++)
 ((char *)output)[i] = (char)value;
}
复制代码

md5头文件

/* MD5.H - header file for MD5C.C
 */
/* MD5 context. */
typedef struct {
  UINT4 state[4];                                   /* state (ABCD) */
  UINT4 count[2];        /* number of bits, modulo 2^64 (lsb first) */
  unsigned char buffer[64];                         /* input buffer */
} MD5_CTX;

void MD5Init PROTO_LIST ((MD5_CTX *));
void MD5Update PROTO_LIST
  ((MD5_CTX *, unsigned char *, unsigned int));
void MD5Final PROTO_LIST ((unsigned char [16], MD5_CTX *));

复制代码