Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <openssl/evp.h>
- // crash message & cleanup
- void crash( EVP_MD_CTX* ctx, const char* msg)
- {
- EVP_MD_CTX_free(ctx);
- fprintf(stderr, "%s\n", msg);
- exit(1);
- }
- int main(int argc, char *argv[])
- {
- // evp structures
- EVP_MD_CTX *mdctx; // EVP Message Digest context
- const EVP_MD *md; // Message Digest
- unsigned char md_value[EVP_MAX_MD_SIZE]; // output byte array (hash accumulates here)
- unsigned int md_len; // length of digest
- // local vars
- const char* prog_name; // this program name
- const char* digest_str; // name of digest "md5" "sha1" "sha224"
- const char* fname; // file to hash
- FILE* inFile = NULL; // input file
- if (argc == 3) // parse args
- {
- prog_name = argv[0];
- digest_str = argv[1];
- fname = argv[2];
- }
- else // bad args
- {
- fprintf(stderr, "no file: specified.\n usage %s <digest> <filename>\n", argv[0]);
- exit(2); // return bad arguments
- }
- // try open file
- inFile = fopen(fname, "rb");
- if ( inFile == NULL ) // fail to open
- {
- fprintf(stderr, "could not open file: %s\n", fname);
- fprintf(stderr, "usage:\t %s <digest> <filename>\n", prog_name );
- exit(1); // fail
- }
- // get digest type
- md = EVP_get_digestbyname(digest_str);
- if (md == NULL) // bad digest name
- {
- fprintf( stderr, "Unknown message digest %s\n", digest_str);
- exit(2);
- }
- // new digest context
- mdctx = EVP_MD_CTX_new();
- if (EVP_DigestInit_ex2(mdctx, md, NULL) == 0 )
- crash(mdctx, "Message digest initialization failed.\n");
- // read data into a buffer and update the hash
- // 1KB at a time
- unsigned char bytedata[1024]; // buffer to read into
- size_t bytes;
- // update digest context with new bytes
- while ( (bytes = fread (bytedata, 1, 1024, inFile)) != 0 )
- {
- if( EVP_DigestUpdate(mdctx, bytedata, 1024) == 0 )
- crash(mdctx, "Message digest update failed.\n");
- }
- // finalize digest
- if (EVP_DigestFinal_ex(mdctx, md_value, &md_len) == 0 )
- crash(mdctx, "Message digest finalization failed.\n");
- // final clean up
- EVP_MD_CTX_free(mdctx); // clean up dynamic memory
- // output
- fprintf(stdout, "%s Digest is: ", digest_str);
- for ( unsigned int i = 0; i < md_len; i++)
- fprintf(stdout, "%02x", md_value[i]); // hex digit
- fprintf(stdout,"\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement