Debian Codegraph @

sha1.c

raw symbols SCIP
1 /* -*- Mode: C; c-file-style: "stroustrup" -*- */
2
3 #include <stdio.h>
4 #include <string.h>
5 #include "sha1.h"
6
7 #define BUFFER_SIZE 1024
8
9 int SHA1_file( char* filename, byte md[ SHA1_DIGEST_BYTES ] )
10 {
11 FILE* file = NULL ;
12 byte buffer[ BUFFER_SIZE ] = {0};
13 size_t bytes_read = 0 ;
14 int opened = 0;
15 SHA1_ctx ctx;
16
17 if ( strcmp( filename, "-" ) == 0 ) {
18 file = stdin;
19 } else {
20 file = fopen( filename, "rb" );
21 if ( file == 0 ) { return -1; }
22 opened = 1;
23 }
24
25 SHA1_Init( &ctx );
26 while ( !feof( file ) ) {
27 bytes_read = fread( buffer, 1, BUFFER_SIZE, file );
28 if ( bytes_read < BUFFER_SIZE && ferror( file ) ) {
29 return -1;
30 }
31 SHA1_Update( &ctx, buffer, bytes_read );
32 }
33 SHA1_Final( &ctx, md );
34 if ( opened ) {
35 fclose( file );
36 }
37 return 0;
38 }
39
40 const char* hex_digest( byte md[ SHA1_DIGEST_BYTES ] )
41 {
42 int i = 0 ;
43 static char hex[ SHA1_DIGEST_BYTES * 2 + 1 ] = {0};
44
45 for ( i = 0; i < SHA1_DIGEST_BYTES; i++ ) {
46 sprintf( hex + 2 * i, "%02x", md[ i ] );
47 }
48 hex[ sizeof( hex ) - 1 ] = '\0';
49 return hex;
50 }
51
52 int main( int argc, char* argv[] )
53 {
54 int i = 0 ;
55 byte digest[ SHA1_DIGEST_BYTES ] = {0};
56 int status = 0 ;
57
58 if ( argc == 1 ) {
59 status = SHA1_file( "-", digest );
60 if ( status < 0 ) {
61 perror( "(stdin)" );
62 } else {
63 printf( "%s\n", hex_digest( digest ) );
64 }
65 } else {
66 for ( i = 1; i < argc; i++ ) {
67 status = SHA1_file( argv[ i ], digest );
68 if ( status < 0 ) {
69 perror( argv[ i ] );
70 return 1;
71 } else {
72 printf( "%s %s\n", hex_digest( digest ), argv[ i ] );
73 }
74 }
75 }
76 return 0;
77 }