C++入门教程(17)MD5加密以及数据校验

本文介绍了MD5在数据校验中的应用,通过一个实例展示了如何使用C++进行MD5加密来防止玩家在游戏充值中篡改数据,从而确保数据安全性。文章包含MD5加密的代码示例,以及数据签名的验证流程。
摘要由CSDN通过智能技术生成

MD5的应用很广泛,可以用于记录文件的md5值以用于检测更新,记录玩家的账号密码等等。

由于它的不可逆性,还可以用于校验数据签名,以验证数据的合法性

某上线应用程序发现有玩家的货币增长异常,经过后台日志发现,玩家某一时刻充值后,并没有立即请求,而是修改了发送的充值金额,由于订单合法,服务器认为是正常的订单,就放过了,但是实际充值的钱和商品的数量是不匹配的,导致玩家刷走了好多货币。

为了防止玩家继续刷币,需要验证发送请求的合法性,增加了一步验证签名的过程

验证过程:

1)服务器下发一串用于签名的密钥,通常是一串字符串

2)客户端需要将发送的数据按照一定的规则,结合密钥得到一个用于签名的字符串,并发送给服务端

3)服务端根据发来的数据和密钥用同样的方式生成签名和客户端的签名进行比对,如果一致,则认为数据是合法的否则认为数据不合法。

md5.h

#ifndef MD5_H
#define MD5_H

#include <string>
#include <fstream>

/* Type define */
typedef unsigned char byte;



//如是是32位的系统
//typedef unsigned long ulong;
//如果是64位的系统
typedef unsigned int ulong;

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 ulong *input, byte *output, size_t length);
	void decode(const byte *input, ulong *output, size_t length);
	string bytesToHexString(const byte *input, size_t length);

	/* class uncopyable */
	MD5(const MD5&);
	MD5& operator=(const MD5&);
private:
	ulong _state[4];	/* state (ABCD) */
	ulong _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];
	static const size_t 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,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱我呦呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值