-
Notifications
You must be signed in to change notification settings - Fork 19
/
sha1num.c
77 lines (66 loc) · 1.59 KB
/
sha1num.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* sha1num.c --- generate sha1 hash based, pseudo random numbers
*
* Copyright (C) 2005 by Olivier Guerrier
*
* This file may be distributed under the terms of the GNU Public
* License.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "pwgen.h"
#include "sha1.h"
sha1_context sha1_ctx;
char *sha1_seed;
const char *sha1_magic="pwgen";
unsigned char sha1sum[20];
int sha1sum_idx=20;
void pw_sha1_init(char *sha1)
{
int i = 0;
char *seed;
FILE *f;
unsigned char buf[1024];
if ((seed = strchr(sha1,'#'))) {
*(seed++) = 0;
sha1_seed = malloc(strlen(seed)+1);
if (!sha1_seed) {
fprintf(stderr, "Couldn't malloc sha1_seed buffer.\n");
exit(1);
}
strcpy(sha1_seed, seed);
}
else {
sha1_seed = malloc(strlen(sha1_magic)+1);
if (!sha1_seed) {
fprintf(stderr, "Couldn't malloc sha1_seed buffer.\n");
exit(1);
}
strcpy(sha1_seed, sha1_magic);
}
if( ! ( f = fopen( sha1, "rb" ) ) ) {
fprintf(stderr, "Couldn't open file: %s.\n", sha1);
exit(1);
}
sha1_starts( &sha1_ctx );
while( ( i = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) {
sha1_update( &sha1_ctx, buf, i );
}
fclose(f);
return;
}
int pw_sha1_number(int max_num)
{
int val;
sha1_context ctx;
if (sha1sum_idx>19) {
sha1sum_idx = 0;
sha1_update(&sha1_ctx, (unsigned char *) sha1_seed,
strlen(sha1_seed));
ctx = sha1_ctx;
sha1_finish(&ctx, sha1sum );
}
val = (int) (sha1sum[sha1sum_idx++] / ((float) 256) * max_num);
return (val);
}