Plan 9 from Bell Labs’s /usr/web/sources/contrib/mycroftiv/unreleased/hashfuncs/crypthash.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


/* these functions operate on incoming null terminated character arrays and produce hashes of the given data of the requested size*/
/* they rely on the following includes, so add these in where you need them:
**#include <mp.h>
**#include <libsec.h>
*/

uint sha1hash(uint ntbl, char* data);
uint md5hash(uint ntbl, char* data);

uint
sha1hash(uint ntbl, char *data)
{
	uint off;
	uint size;
	uint tmpsize;
	uint bitcount;
	uint bytecount;
	uchar hashdigest[SHA1dlen];

	size = strlen(data);	/* we're assuming we are given correctly string terminated data */

	sha1((uchar*)data, size, hashdigest, nil);		/* get the base sha1hash of our data */

/* the space of sha1hashes is huge compared to any sane hashtable size. so, we count how many bytes of data are needed to distribute our sha1 space across our hashtable size, and we round up. */
	bitcount = 0;
	tmpsize = ntbl;
	while(tmpsize > 0) {
		tmpsize >>= 1;
		bitcount++;
	}
	bytecount = (bitcount / 8) + 1;
	
/* now that we know how many bytes we want, lets get an integer from that many bytes of our hash */
	tmpsize = 1;
	off = (uint)hashdigest[0];
	for(int i = 1; i < bytecount; i++){
		tmpsize = tmpsize * 256;		/* since we are moving byte to byte, this is base 256 */
		off +=  tmpsize * (uint)hashdigest[i];
	}

	return off % ntbl;	/* we rounded up on bytes so we need to modulo our table size */
}

uint
md5hash(uint ntbl, char *data)
{
	uint off;
	uint size;
	uint tmpsize;
	uint bitcount;
	uint bytecount;
	uchar hashdigest[MD5dlen];

	size = strlen(data);

	md5((uchar*)data, size, hashdigest, nil);

	bitcount = 0;
	tmpsize = ntbl;
	while(tmpsize > 0) {
		tmpsize >>= 1;
		bitcount++;
	}
	bytecount = (bitcount / 8) + 1;
	
	tmpsize = 1;
	off = (uint)hashdigest[0];
	for(int i = 1; i < bytecount; i++){
		tmpsize = tmpsize * 256;
		off +=  tmpsize * (uint)hashdigest[i];
	}

	return off % ntbl;
}

/* note these two functions are completely identical save for the call to the given hash function */
/* implemented by mycroftiv  */

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.