Skip to content

Instantly share code, notes, and snippets.

@odzhan
Last active October 18, 2020 03:53
Show Gist options
  • Save odzhan/f163f16c5bb9e922fefca9579af6b3bd to your computer and use it in GitHub Desktop.
Save odzhan/f163f16c5bb9e922fefca9579af6b3bd to your computer and use it in GitHub Desktop.
Derive a cryptographic hash from file using Windows Crypto API
/**
BSD 3-Clause License
Copyright (c) 2016 Odzhan. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "shell32.lib")
// read 1MB chunks for hashing
#define READ_BLOCK_SIZE 1048576
// for hexdumping and base64
#define MAXBUF 512
// phony ALG_IDs
#define CALG_BASE64 -1 // same as CALG_OID_INFO_CNG_ONLY
#define CALG_HEXDUMP -2 // same as CALG_OID_INFO_PARAMETERS
// bit like hexdump / xxd except very very slow .. :(
BOOL hexdump(PVOID input, ULONG64 inlen) {
DWORD outlen, rd;
ULONG64 ofs;
CHAR out[128];
PBYTE ptr=(PBYTE)input;
BOOL r = FALSE;
// print every 16 bytes as one line
for(ofs=0; ofs<inlen;) {
rd = (ofs + 16) < inlen ? 16 : (inlen - ofs);
// convert to hex
outlen = sizeof(out);
r = CryptBinaryToString(ptr, rd,
CRYPT_STRING_HEXASCII | CRYPT_STRING_NOCR,
out, &outlen);
if(!r) break;
printf("%p: %s", (PVOID)ofs, out);
// update length and pointer
ofs += rd;
ptr += rd;
}
return r;
}
// convert string to base64
// slow as hell. reads in chunks of 255 bytes
BOOL base64(PVOID input, ULONG64 inlen) {
DWORD outlen, rd;
ULONG64 ofs;
CHAR out[((4 * 255) + 4) & -4];
PBYTE ptr=(PBYTE)input;
BOOL r = FALSE;
// convert binary to base64
for(ofs=0; ofs<inlen;) {
rd = ((ofs + 255) <= inlen) ? 255 : (inlen - ofs);
// convert to hex
outlen = sizeof(out);
r = CryptBinaryToString(ptr, rd,
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
out, &outlen);
if(!r) break;
fwrite(out, 1, outlen, stdout);
// update length and pointer
ofs += rd;
ptr += rd;
}
return r;
}
/**F*****************************************************************/
BOOL hash_file (const CHAR file_path[], BYTE hash[], PDWORD len, ALG_ID id, BOOL verbose)
/**
* PURPOSE : create hash of file using AES crypto provider
*
* RETURN : TRUE or FALSE
*
* NOTES : XP doesn't support SHA-256 it so needs changing to use SHA-1
*
*F*/
{
HCRYPTPROV hp;
HCRYPTHASH hh;
HANDLE hf, hm = NULL;
DWORD rd, i, prov_type = PROV_RSA_AES;
ULONG64 fs, cmp;
BOOL r = FALSE;
PVOID mem = NULL;
PBYTE ptr;
// try open file for reading
hf = CreateFile(file_path, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hf == INVALID_HANDLE_VALUE) return FALSE;
// read the size
GetFileSizeEx(hf, (LARGE_INTEGER*)&fs);
// try create file map
hm = CreateFileMapping(hf, NULL, PAGE_READONLY, 0, 0, NULL);
if(hm == NULL) goto cleanup;
// map view of file
mem = (LPBYTE)MapViewOfFile(hm, FILE_MAP_READ, 0, 0, 0);
if(mem == NULL) goto cleanup;
if(id == CALG_BASE64) {
// base64?
r = base64(mem, fs);
} else if (id == CALG_HEXDUMP) {
// hexdump?
r = hexdump(mem, fs);
} else {
// if using legacy algorithm, switch to legacy provider
if(id == CALG_MD2 || id == CALG_MD4 || id == CALG_MD5) {
prov_type = PROV_RSA_FULL;
}
// acquire a crypto context
r = CryptAcquireContext(&hp, NULL, NULL,
prov_type, CRYPT_VERIFYCONTEXT);
if(r) {
// create a hash object
r = CryptCreateHash(hp, id, 0, 0, &hh);
if(r) {
// hash data
for(ptr=(PBYTE)mem, cmp=0; cmp<fs;) {
rd = ((cmp + READ_BLOCK_SIZE) <= fs) ? READ_BLOCK_SIZE : (fs - cmp);
// update hash object
CryptHashData(hh, ptr, rd, 0);
cmp += rd;
ptr += rd;
// if verbose output requested, print message every 100MB
if(verbose && (cmp % (102400 * 100)) == 0) {
printf(" [ processed %"PRIu64 " of %"PRIu64 " - %"PRIu64" %% complete\r",
cmp, fs, (100 * cmp) / fs);
}
}
r = CryptGetHashParam(hh, HP_HASHVAL, hash, len, 0);
CryptDestroyHash(hh);
}
CryptReleaseContext(hp, 0);
}
}
cleanup:
if(mem != NULL) UnmapViewOfFile(mem);
if(hm != NULL) CloseHandle(hm);
CloseHandle(hf);
return r;
}
/**F*****************************************************************/
BOOL hash_string(const PCHAR input, PBYTE hash, PDWORD len, ALG_ID id, BOOL unicode)
/**
* PURPOSE : create hash of input string
*
* RETURN : TRUE or FALSE
*
* NOTES : XP doesn't support SHA-256 it so needs changing to use SHA-1
*
*F*/
{
HCRYPTPROV hp;
HCRYPTHASH hh;
DWORD inlen, prov_type = PROV_RSA_AES;
BOOL r;
inlen = lstrlen(input);
if(id == CALG_BASE64) {
// base64?
r = base64(input, inlen);
} else if (id == CALG_HEXDUMP) {
// hexdump?
r = hexdump(input, inlen);
} else {
// if using legacy algorithm, switch to legacy provider
if(id == CALG_MD2 || id == CALG_MD4 || id == CALG_MD5) {
prov_type = PROV_RSA_FULL;
}
// acquire a crypto context
r = CryptAcquireContext(&hp, NULL, NULL,
prov_type, CRYPT_VERIFYCONTEXT);
if(r) {
// create a hash object
r = CryptCreateHash(hp, id, 0, 0, &hh);
if(r) {
// update hash object
r = CryptHashData(hh, input, inlen, 0);
CryptGetHashParam(hh, HP_HASHVAL, hash, len, 0);
CryptDestroyHash(hh);
}
CryptReleaseContext(hp, 0);
}
}
return r;
}
void usage(void) {
printf("\n");
printf(" [ usage: hashfile /<alg> /s /v <input>\n\n");
printf(" [ /<alg> : base64, hex, md2, md4, md5, sha1, sha256, sha384 or sha512.\n");
printf(" [ /s : Input is a string. Default input is a file.\n");
printf(" [ /v : Verbose output for file hashing.\n");
// TODO: printf(" [ /u : Combined with /s, string input is converted to unicode before hashing.\n\n");
exit(0);
}
int main(int argc, char *argv[]) {
PCHAR alg="SHA-256", arg = NULL;
DWORD i, len;
BOOL verbose = FALSE, str = FALSE, unicode = FALSE;
ALG_ID id = CALG_SHA_256; // default is SHA-256
BYTE hash[128];
if(argc == 1) {
usage();
}
// parse arguments
for(i=0; i<argc; i++) {
if(argv[i][0]=='/' || argv[i][0]=='-') {
// hash algorithm?
if(!lstrcmp(&argv[i][1], "md2")) { alg="MD2"; id = CALG_MD2; continue; }
if(!lstrcmp(&argv[i][1], "md4")) { alg="MD4"; id = CALG_MD4; continue; }
if(!lstrcmp(&argv[i][1], "md5")) { alg="MD5"; id = CALG_MD5; continue; }
if(!lstrcmp(&argv[i][1], "sha1")) { alg="SHA-1"; id = CALG_SHA1; continue; }
if(!lstrcmp(&argv[i][1], "sha256")) { alg="SHA-256"; id = CALG_SHA_256; continue; }
if(!lstrcmp(&argv[i][1], "sha384")) { alg="SHA-384"; id = CALG_SHA_384; continue; }
if(!lstrcmp(&argv[i][1], "sha512")) { alg="SHA-512"; id = CALG_SHA_512; continue; }
if(!lstrcmp(&argv[i][1], "base64")) { alg="Base64"; id = CALG_BASE64; continue; }
if(!lstrcmp(&argv[i][1], "hex")) { alg="HexDump"; id = CALG_HEXDUMP; continue; }
// help?
if(argv[i][1] == '?' || argv[i][1] == 'h' || !lstrcmp(&argv[i][1], "-help")) { usage(); }
// verbose on?
if(argv[i][1] == 'v') { verbose=TRUE; continue; }
// input string?
if(argv[i][1] == 's') { str = TRUE; continue; }
// convert input string to unicode?
if(argv[i][1] == 'u') { unicode = TRUE; continue; }
printf("unrecognized : %s\n", argv[i]);
usage();
} else {
// assume it's a path to file
arg = argv[i];
}
}
// no file? display error
if(arg == NULL) {
printf("No input specified.\n");
usage();
}
if(!str) {
// derive hash from file input
len = sizeof(hash);
if(!hash_file(arg, hash, &len, id, verbose)) {
printf("unable to hash file : %s\n", arg);
return 0;
}
} else {
// derive hash from string input
len = sizeof(hash);
if(!hash_string(arg, hash, &len, id, unicode)) {
printf("unable to hash string : %s\n", arg);
return 0;
}
}
if(id != CALG_HEXDUMP && id != CALG_BASE64) {
printf("%s(%s) : ", alg, arg);
for(i=0; i<len; i++) {
printf("%02x", hash[i]);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment