文件Md5计算(C语言版)
这是一个参考了网上很多人的C语言以及C++版本的计算工具而制作的,已对其优化了一部分,加了新功能:如果能计算出有效的Md5则自动复制到剪贴板,并且支持拖拽文件到窗口上,完全可以适合当一个小工具了。
废话不多说,直接上源代码,本人是在VS2019工程下编译的。
开源地址:
https://github.com/Liushui-Miaomiao/FileMd5.git
https://gitee.com/liushui_miaomiao/FileMd5.git
FileMd5.h:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include "Md5.h"
#include "clipboard.h"
FileMd5.c:
#include "FileMd5.h"
int main(void){
SetConsoleTitleA("FileMd5");
char* l_p_filePath = NULL;
char* l_p_fileMd5 = NULL;
while (TRUE) {
l_p_filePath = NULL;
l_p_fileMd5 = NULL;
l_p_filePath = (char*)malloc(256);
l_p_fileMd5 = (char*)malloc(32);
if (!l_p_filePath || !l_p_fileMd5) {
puts("Failed to allocate memory!");
free(l_p_filePath);
free(l_p_fileMd5);
exit(EXIT_FAILURE);
}
printf("Please enter the file path:");
gets_s(l_p_filePath, 255);
if (!strcmp(l_p_filePath, "exit")) {
free(l_p_filePath);
free(l_p_fileMd5);
break;
}
//Deal with double quotes.
int l_len = strlen(l_p_filePath);
if (l_p_filePath[l_len - 1] == '\"') {
l_p_filePath[l_len - 1] = '\0';
}
if (l_p_filePath[0] == '\"') {
strcpy_s(l_p_filePath, l_len, l_p_filePath + 1);
}
l_p_fileMd5 = GetFileMd5(l_p_filePath);
if (l_p_fileMd5) {
printf("Md5 Code:%s\n", l_p_fileMd5);
if (!WriteClipboard(l_p_fileMd5)) {
puts("Failed to write to clipboard!");
}
putchar('\n');
continue;
}
puts("Failed to open file!");
}
return EXIT_SUCCESS;
}
Md5.h:
#pragma once
char* GetFileMd5(char* filePath);
Md5.c:(核心算法)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Md5.h"
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
//x << y
#define RL(x, y) (((x) << (y)) | ((x) >> (32 - (y))))
//PP(aabbccdd)=ddccbbaa
#define PP(x) (x<<24)|((x<<8)&0xff0000)|((x>>8)&0xff00)| (x>>24)
#define FF(a, b, c, d, x, s, ac) a = b + (RL((a + F(b,c,d) + x + ac),s))
#define GG(a, b, c, d, x, s, ac) a = b + (RL((a + G(b,c,d) + x + ac),s))
#define HH(a, b, c, d, x, s, ac) a = b + (RL((a + H(b,c,d) + x + ac),s))
#define II(a, b, c, d, x, s, ac) a = b + (RL((a + I(b,c,d) + x + ac),s))
static FILE* GetFileFP(char* filePath);
static void Md5(void);
/*
i: Temp variable
len: The length of the file
flen: The initial leng of a file represented by a 64-bits binary
*/
static unsigned A = 0;
static unsigned B = 0;
static unsigned C = 0;
static unsigned D = 0;
static unsigned a = 0;
static unsigned b = 0;
static unsigned c = 0;
static unsigned d = 0;
static unsigned i = 0;
static unsigned len = 0;
static unsigned flen[2] = {
0, 0};
static unsigned x[16] = {
0, 0, 0, 0, 0