MD5验证文件完整性 C++

通过C++编程,利用MD5算法进行文件完整性验证,确保下载的文件未被篡改。主要涉及读取文件内容并以二进制模式进行MD5计算,生成32位校验码。
摘要由CSDN通过智能技术生成

读取文件内容并且做MD5验证 C++

为了验证下载的文件是否完整,是否被篡改,常用的验证方法为MD5验证,文件生成32位验证码,可验证文件是否完整下载或被篡改。

md5.h文件

#ifndef MD5_H
#define MD5_H
 
#include <string>
#include <fstream>
 
/* Type define */
typedef unsigned char byte;
typedef unsigned int uint32;
 
using std::string;
using std::ifstream;
 
/* MD5 declaration. */
class MD5 {
public:
MD5();
MD5(const void* input, size_t length);
MD5(const string& str);
MD5(ifstream& in);
void update(const void* input, size_t length);
void update(const string& str);
void update(ifstream& in);
const byte* digest();
string toString();
void reset();
 
private:
void update(const byte* input, size_t length);
void final();
void transform(const byte block[64]);
void encode(const uint32* input, byte* output, size_t length);
void decode(const byte* input, uint32* output, size_t length);
string bytesToHexString(const byte* input, size_t length);
 
/* class uncopyable */
MD5(const MD5&);
MD5& operator=(const MD5&);
 
private:
uint32 _state[4]; /* state (ABCD) */
uint32 _count[2]; /* number of bits, modulo 2^64 (low-order word first) */
byte _buffer[64]; /* input buffer */
byte _digest[16]; /* message digest */
bool _finished;   /* calculate finished ? */
 
static const byte PADDING[64]; /* padding for calculate */
static const char HEX[16];
enum { BUFFER_SIZE = 1024 };
};
 
#endif /*MD5_H*/

md5.cpp文件

#include "md5.h"
 
using namespace std;
 
/* Constants for MD5Transform routine. */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
 
 
/* F, G, H and I are basic MD5 functions.
*/
#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)))
 
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
 
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值