Created
April 7, 2014 09:16
-
-
Save yuikns/10017122 to your computer and use it in GitHub Desktop.
generate hash key from a string , should init first
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 <string.h> | |
#include <stdio.h> | |
static unsigned long crypt[0x500]; | |
void crypt_init(); | |
#define PRIME_SIZE 32 | |
static const unsigned long prime_list[PRIME_SIZE] = | |
{ | |
0ul, 3ul, 11ul, 23ul, 53ul, | |
97ul, 193ul, 389ul, 769ul, 1543ul, | |
3079ul, 6151ul, 12289ul, 24593ul, 49157ul, | |
98317ul, 196613ul, 393241ul, 786433ul, 1572869ul, | |
3145739ul, 6291469ul, 12582917ul, 25165843ul, 50331653ul, | |
100663319ul, 201326611ul, 402653189ul, 805306457ul, 1610612741ul, | |
3221225473ul, 4294967291ul | |
}; | |
void crypt_init() | |
{ | |
unsigned long seed = 0x00100001, idx_a = 0, idx_b = 0, i; | |
for( idx_a = 0; idx_a < 0x100; idx_a++ ) | |
{ | |
for( idx_b = idx_a, i = 0; i < 5; i++, idx_b += 0x100 ) | |
{ | |
unsigned long t1, t2; | |
seed = (seed * 125 + 3) % 0x2AAAAB; | |
t1 = (seed & 0xFFFF) << 0x10; | |
seed = (seed * 125 + 3) % 0x2AAAAB; | |
t2 = (seed & 0xFFFF); | |
crypt[idx_b] = ( t1 | t2 ); | |
} | |
} | |
} | |
unsigned long hkg(const unsigned char * k, unsigned long offset) | |
{ | |
unsigned long seed_a = 0x7FED7FED, seed_b = 0xEEEEEEEE; | |
unsigned long ch; | |
while(*k != 0) | |
{ | |
ch = (*k++); | |
//ch = toupper(*k++); | |
seed_a = crypt[(offset << 8) + ch] ^ (seed_a + seed_b); | |
seed_b = ch + seed_a + seed_b + (seed_b << 5) + 3; | |
} | |
return seed_a; | |
} | |
int main(int argc,char * argv[]) | |
{ | |
crypt_init(); | |
const char * a0 = "string a"; | |
const char * a1 = "string a"; | |
const char * a2 = "STRING a"; | |
const char * a3 = "string b"; | |
const char * a4 = "中文 "; | |
const char * a5 = "中文2"; | |
int i ; | |
for(i = 0 ; i <PRIME_SIZE; i++ ) | |
{ | |
printf("[%2d] %-5lu\t",i,prime_list[i]); | |
if((i+1) % 5 == 0 ) printf("\n"); | |
} | |
printf("\n"); | |
printf("%lu ~ %lu\n",hkg(a0,0),hkg(a0,0)%prime_list[11]); | |
printf("%lu ~ %lu\n",hkg(a0,0),hkg(a0,0)%prime_list[15]); | |
printf("%lu\n",hkg(a1,0)); | |
printf("%lu\n",hkg(a2,0)); | |
printf("%lu\n",hkg(a3,0)); | |
printf("%lu\n",hkg(a4,0)); | |
printf("%lu\n",hkg(a5,0)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment