"Fossies" - the Fresh Open Source Software Archive

Member "pwgen-2.08/sha1num.c" (7 Aug 2017, 1631 Bytes) of package /linux/privat/pwgen-2.08.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "sha1num.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.07_vs_2.08.

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