Created
October 2, 2011 21:08
-
-
Save antirez/1257955 to your computer and use it in GitHub Desktop.
antirez hashing function #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Description of AHF1 algorithm: | |
Initialize the four bytes H[0], H[1], H[2], H[3] to respectively 8D CA 2E 35 | |
Initialize IDX to 0 | |
For each byte B in the string to hash: | |
TARGET = (B XOR H[IDX]) MOD 4 | |
H[TARGET] = H[TARGET] XOR B | |
ROTATION = B MOD 16 | |
Use H0, H1, H2, H3 to compose a 32 bit sequence where H0 is the least significant | |
byte and H3 is the most significant byte, then rotate the sequence by "ROTATION" | |
bits using a circular shifting. Finally Set H0, H1, H2, H3 to the new bits. | |
IDX = IDX+1 MOD 4 | |
The output of the hash function is the 32 bit integer composed by H0, H1, H2, H3 where | |
H0 is the LSB and H3 the MSB. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <sys/types.h> | |
/* antirez hash function one (AHF1) | |
* | |
* FIXME: make it byte ordering agnostic. | |
* | |
* TEST VECTOR: | |
* "123456789" => 2934016909 | |
* "Message Digest" => 1454815842 | |
*/ | |
uint32_t ahf1(unsigned char *s, size_t len) { | |
uint32_t hash; | |
unsigned char *h = (unsigned char*) &hash; | |
int idx = 0; | |
h[0] = 0x8D; | |
h[1] = 0xCA; | |
h[2] = 0x2E; | |
h[3] = 0x35; | |
while(len) { | |
int target = ((*s) ^ h[idx]) & 3; | |
int rot = *s & 0x1F; | |
h[target] ^= *s; /* step 1: XOR with target byte. */ | |
hash = (hash << rot) | (hash >> (32-rot)); /* step 2: Circular shifting. */ | |
len--; | |
s++; | |
idx = (idx+1) & 3; | |
} | |
return hash; | |
} | |
#include <stdio.h> | |
#include <string.h> | |
int main(void) { | |
printf("%lu\n", (unsigned long) ahf1((unsigned char*)"123456789",9)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment