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,