md5计算程序源代码
java中常用的md5方法

java中常用的md5方法Java是一种广泛使用的编程语言,特别适合用于开发各种类型的应用程序。
在Java中,MD5(Message-Digest Algorithm 5)是一种常用的哈希算法,用于产生唯一的消息摘要。
本文将详细介绍在Java中常用的MD5方法。
第一步:导入相关的包使用MD5算法需要导入Java的Security包。
在代码的开头加上以下导入语句:import java.security.MessageDigest;第二步:创建一个方法在Java中,我们可以创建一个方法用于计算MD5消息摘要。
下面是一个示例:public static String getMD5(String input) {try {MessageDigest md =MessageDigest.getInstance("MD5"); 创建MD5加密对象byte[] messageDigest = md.digest(input.getBytes()); 获取二进制摘要值转化为十六进制字符串形式StringBuilder hexString = new StringBuilder();for (byte b : messageDigest) {String hex = Integer.toHexString(0xFF & b);if (hex.length() == 1) {hexString.append('0');}hexString.append(hex);}return hexString.toString();} catch (Exception ex) {ex.printStackTrace();return null;}}第三步:调用方法要使用这个方法,只需在代码中调用getMD5()方法,并传递要进行MD5加密的消息作为参数。
以下是一个使用示例:String input = "Hello World";String md5Hash = getMD5(input);System.out.println("MD5加密后的结果:" + md5Hash);以上代码将输出:MD5加密后的结果:0a4d55a8d778e5022fab701977c5d840第四步:解释代码让我们来解释一下上面的代码。
VB.net的MD5代码

的MD5代码原文:/link?url=VBUqC6fqVp5OB3mhfzlphknuY HwNqtO-VWq0tahehkdWx_ECIWOZCEWw6X0opDTf[vb]view plaincopyprint?1.Imports System2.Imports System.Security.Cryptography3.Imports System.Text4.Module Example5.' 哈希输入字符串并返回一个32字符的十六进制字符串哈希。
6.Function getMd5Hash(ByVal input As String) As String7.' 创建新的一个MD5CryptoServiceProvider对象的实例。
8.Dim md5Hasher As New MD5CryptoServiceProvider()9.' 输入的字符串转换为字节数组,并计算哈希。
10.Dim data As Byte() = puteHash(Encod ing.Default.GetBytes(input))11.' 创建一个新的StringBuilder收集的字节,并创建一个字符串。
12.Dim sBuilder As New StringBuilder()13.' 通过每个字节的哈希数据和格式为十六进制字符串的每一个循环。
14.Dim i As Integer15.For i = 0 To data.Length - 116.sBuilder.Append(data(i).ToString("x2"))17.Next i18.' 返回十六进制字符串。
19.Return sBuilder.ToString()20.End Function21.' 验证对一个字符串的哈希值。
22.Function verifyMd5Hash(ByVal input As String,ByVal h ash As String) As Boolean23.' 哈希的输入。
MD5算法及源代码

MD5算法及源代码分类:计算机密码//获得MD5的二个数组和一个buffer并初始化MD5 *GetMD5();//初始化MD5的二个数据和一个buffervoid MD5Init (MD5 *context);//用于计算MD5值的函数void MD5Update (MD5 *context, unsigned char *input, unsigned int inputLen);//输出结果void MD5Final (MD5 *context, unsigned char digest[16]);//对input数据做一次完整的MD5运算void MD5Out (MD5 *md5, unsigned char *input, unsigned int inputLen, unsigned char out[16]);//计算一个文件的MD5值int 计算一个文件的MD5值(TCHAR* 文件路径, unsigned char md5值[16]){MD5 context;int 缓冲区长度 = 1024,读取到的字节数;unsigned char *缓冲区 = new unsigned char[缓冲区长度];FILE *文件指针 = fopen(文件路径, "rb");if(文件指针 == NULL)return 1;MD5Init(&context);while ( (读取到的字节数 = fread (缓冲区, 1, 缓冲区长度, 文件指针 )) ! =EOF){MD5Update (&context, 缓冲区, 读取到的字节数);//判断是否为已经读到文件尾if ( 读取到的字节数 < 缓冲区长度 )break;}MD5Final (&context, md5值);free ( 缓冲区 );return 0;}/****MD5.h**/typedef struct {unsigned long state[4]; /* state (ABCD) */unsigned long count[2]; /* number of bits, modulo 2^64 */unsigned char buffer[64]; /* input buffer */} MD5;MD5 *GetMD5();void MD5Init (MD5 *context);void MD5Update (MD5 *context, unsigned char *input, unsigned int inputLen);void MD5Final (MD5 *context, unsigned char digest[16]);void MD5Out (MD5 *md5, unsigned char *input, unsigned int inputLen, unsigned char out[16]); /***MD5.cpp*/#include "stdafx.h"#include <string.h>#include "md5.h"#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 21static void MD5Transform (unsigned long int state[4], unsigned char block[64]);static void Encode (unsigned char *output, unsigned long int *input,unsigned int len); static void Decode (unsigned long int *output, unsigned char *input, unsigned int len);//static void MD5_memcpy (unsigned char* output, unsigned char* input,unsigned int len);//static void MD5_memset (unsigned char* output,int value,unsigned int len);static unsigned char PADDING[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};/* 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) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}#define GG(a, b, c, d, x, s, ac) { \(a) += G ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}#define HH(a, b, c, d, x, s, ac) { \(a) += H ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}#define II(a, b, c, d, x, s, ac) { \(a) += I ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}MD5 *GetMD5(){MD5 *md5 = new MD5();MD5Init(md5);return md5;}void MD5Init (MD5 *context){context->count[0] = context->count[1] = 0;/* Load magic initialization constants.*/context->state[0] = 0x67452301;context->state[1] = 0xefcdab89;context->state[2] = 0x98badcfe;context->state[3] = 0x10325476;}/* MD5 block update operation. Continues an MD5 message-digestoperation, processing another message block, and updating thecontext.*/void MD5Update (MD5 *context, unsigned char *input, unsigned int inputLen){unsigned int i, index, partLen;/* Compute number of bytes mod 64 */index = (unsigned int)((context->count[0] >> 3) & 0x3F);/* Update number of bits */if ((context->count[0] += ((unsigned long int)inputLen << 3))< ((unsigned long int)inputLen << 3))context->count[1]++;context->count[1] += ((unsigned long int)inputLen >> 29);partLen = 64 - index;/* Transform as many times as possible.*/if (inputLen >= partLen) {memcpy((unsigned char*)&context->buffer[index],(unsigned char*)input, partLen);MD5Transform (context->state, context->buffer);for (i = partLen; i + 63 < inputLen; i += 64)MD5Transform (context->state, &input[i]);index = 0;}elsei = 0;/* Buffer remaining input */memcpy ((unsigned char*)&context->buffer[index], (unsigned char*)&input[i], inputLen-i); }/* MD5 finalization. Ends an MD5 message-digest operation, writing thethe message digest and zeroizing the context.*/void MD5Final (MD5 *context, unsigned char digest[16]){unsigned char bits[8];unsigned int index, padLen;/* Save number of bits */Encode (bits, context ->count, 8);/* Pad out to 56 mod 64.*/index = (unsigned int)((context->count[0] >> 3) & 0x3f);padLen = (index < 56) ? (56 - index) : (120 - index);MD5Update ( context, PADDING, padLen);/* Append length (before padding) */MD5Update (context, bits, 8);/* Store state in digest */Encode (digest, context->state, 16);MD5Init(context);}void MD5Out(MD5 *md5, unsigned char *input, unsigned int inputLen, unsigned char out[16]) {MD5Update(md5, input, inputLen);MD5Final(md5, out);}/* MD5 basic transformation. Transforms state based on block.*/void MD5Transform (unsigned long int state[4], unsigned char block[64]){unsigned long int a = state[0], b = state[1], c = state[2], d = state[3], x[16]; Decode (x, block, 64);/* Round 1 */FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 *//* Round 2 */GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 *//* Round 3 */HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 *//* Round 4 */II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */state[0] += a;state[1] += b;state[2] += c;state[3] += d;/* Zeroize sensitive information.*/memset ((unsigned char*)x, 0, sizeof (x));}/* Encodes input (unsigned long int) into output (unsigned char). Assumes len is a multiple of 4.*/void Encode (unsigned char *output, unsigned long int *input,unsigned int len) {unsigned int i, j;for (i = 0, j = 0; j < len; i++, j += 4) {output[j] = (unsigned char)(input[i] & 0xff);output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);}}/* Decodes input (unsigned char) into output (unsigned long int). Assumes len is a multiple of 4.*/void Decode (unsigned long int *output, unsigned char *input, unsigned int len) {unsigned int i, j;for (i = 0, j = 0; j < len; i++, j += 4)output[i] = ((unsigned long int)input[j]) | (((unsigned long int)input[j+1]) << 8) | (((unsigned long int)input[j+2]) << 16) | (((unsigned long int)input[j+3]) << 24); }。
加密系列MD5加密和解密算法详解代码示例

加密系列MD5加密和解密算法详解代码示例MD5加密算法是一种广泛应用的密码加密算法,它将任意长度的数据映射为固定长度的128位哈希值。
MD5加密算法是不可逆的,即通过密文无法还原得到原始数据。
MD5加密算法的实现可以通过编写代码来完成。
下面是一个示例的MD5加密算法的代码:```import hashlibdef md5_encrypt(data):md5 = hashlib.md5md5.update(data.encode('utf-8'))return md5.hexdigestif __name__ == '__main__':data = input("请输入需要加密的数据:")encrypted_data = md5_encrypt(data)print("加密结果为:", encrypted_data)```以上代码实现了一个简单的MD5加密算法。
首先导入了`hashlib`模块,该模块提供了一系列用于数据加密的算法,包括MD5算法。
`md5_encrypt`函数接收一个字符串作为输入数据,并将其转换为字节流形式,然后使用`hashlib.md5`方法创建了一个MD5对象。
接着,通过调用MD5对象的`update`方法将输入数据添加到加密流程中。
最后,通过调用MD5对象的`hexdigest`方法获得加密后的结果,并将其返回。
在`if __name__ == '__main__'`下方的代码段中,首先获取用户输入的数据,然后调用`md5_encrypt`函数对其进行加密,并将结果打印到控制台。
下面是MD5解密算法的示例代码:```import hashlibdef md5_decrypt(encrypted_data):md5 = hashlib.md5md5.update(encrypted_data.encode('utf-8'))return md5.hexdigestif __name__ == '__main__':encrypted_data = input("请输入需要解密的数据:")decrypted_data = md5_decrypt(encrypted_data)print("解密结果为:", decrypted_data)```以上代码实现了一个简单的MD5解密算法。
详解C#实现MD5加密的示例代码

详解C#实现MD5加密的⽰例代码C#实现MD5加密,具体如下:⽅法⼀⾸先,先简单介绍⼀下MD5MD5的全称是message-digest algorithm 5(信息-摘要算法,在90年代初由mit laboratory for computer science和rsa data security inc的ronald l. rivest开发出来,经md2、md3和md4发展⽽来。
MD5具有很好的安全性(因为它具有不可逆的特征,加过密的密⽂经过解密后和加密前的东东相同的可能性极⼩)引⽤using System.Security.Cryptography;using System.Text;具体代码如下(写在按钮的Click事件⾥):byte[] result = Encoding.Default.GetBytes(this.tbPass.Text.Trim()); //tbPass为输⼊密码的⽂本框MD5 md5 = new MD5CryptoServiceProvider();byte[] output = puteHash(result);this.tbMd5pass.Text = BitConverter.ToString(output).Replace("-",""); //tbMd5pass为输出加密⽂本的⽂本框⽅法⼆C# md5加密(上)string a; //加密前数据string b; //加密后数据b=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a,"MD5")using System;using System.Security.Cryptography;⽅法2public static string GetMD5(string myString){MD5 md5 = new MD5CryptoServiceProvider();byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);byte[] targetData = puteHash(fromData);string byte2String = null;for (int i=0; i<targetData.Length; i++){byte2String += targetData[i].ToString("x");}return byte2String;}using System.Security.Cryptography;/// <summary>/// 给⼀个字符串进⾏MD5加密/// </summary>/// <param name="strText">待加密字符串</param>/// <returns>加密后的字符串</returns>public static string MD5Encrypt(string strText){MD5 md5 = new MD5CryptoServiceProvider();byte[] result = puteHash(System.Text.Encoding.Default.GetBytes(strText));return System.Text.Encoding.Default.GetString(result);}C# MD5加密using System.Security.Cryptography;private void btnOK_Click(object sender, System.EventArgs e){string strConn = "server=192.168.0.51;database=chengheng;User id=sa; password=123";if(texName.Text.Trim()==""){this.RegisterStartupScript("sf","<script language='javascript'>alert('⽤户名不能为空');document.all('texName').focus()</script>"); return;}else if(texPassword.Text.Trim()==""){this.RegisterStartupScript("sfs","<script language='javascript'>alert('密码不能为空');document.all('texPassword').focus()</script>"); return;}else{//将获取的密码加密与数据库中加了密的密码相⽐较byte[] by = puteHash(utf.GetBytes(texPassword.Text.Trim()));string resultPass = System.Text.UTF8Encoding.Unicode.GetString(by);conn.ConnectionString=strConn;SqlCommand comm = new SqlCommand();string name = texName.Text.Trim().ToString();mandText="select Ruser_pwd,Ruser_nm from Ruser where Accountno = @name";comm.Parameters.Add("@name",SqlDbType.NVarChar,40);comm.Parameters["@name"].Value=name;try{conn.Open();comm.Connection=conn;SqlDataReader dr=comm.ExecuteReader();if(dr.Read()){//⽤户存在,对密码进⾏检查if(dr.GetValue(0).Equals(resultPass)){string user_name=dr.GetValue(1).ToString();string user_Accountno=texName.Text.Trim();Session["logon_name"]=user_name;Session["logon_Accountno"]=user_Accountno;//登录成功,进⾏页⾯导向}else{this.RegisterStartupScript("wp","<script language='javascript'>alert('密码错误,请检查。
MD5加密C语言实现

MD5加密C语言实现MD5 (Message Digest Algorithm 5) 是一种常用的密码散列函数,用于将数据加密为128位长度的摘要。
在C语言中,可以通过一系列步骤来实现MD5加密算法。
1.准备工作:首先需要包含一些C标准头文件和预定义常量。
在C语言中,可以使用以下代码来实现:```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdint.h>#define HASH_LENGTH 16```2.定义数据结构:MD5算法涉及到一个64字节的消息块和一个4字节的消息摘要块。
在C语言中,可以使用以下代码来定义这些结构:```ctypedef structuint8_t data[64];uint32_t datalen;uint32_t bitlen[2];uint32_t state[4];}MD5_CTX;typedef uint8_t (*hash_function)(uint8_t *);```3.定义常量和函数:MD5算法使用到一些常量和函数。
在C语言中,可以使用以下代码来定义这些常量和函数:```cconst uint32_t k[64] =// more constants ...};const uint32_t r[64] =7,12,17,22,7,12,17,22,// more constants ...};void md5_transform(MD5_CTX *ctx, uint8_t data[]);void md5_init(MD5_CTX *ctx)ctx->datalen = 0;ctx->bitlen[0] = 0;ctx->bitlen[1] = 0;ctx->state[1] = 0xEFCDAB89;ctx->state[2] = 0x98BADCFE;void md5_update(MD5_CTX *ctx, uint8_t data[], uint32_t len) for (uint32_t i = 0; i < len; i++)ctx->data[ctx->datalen] = data[i];ctx->datalen++;if (ctx->datalen == 64)md5_transform(ctx, ctx->data);ctx->bitlen[0] += 512;ctx->bitlen[1] += (ctx->bitlen[0] < 512);ctx->datalen = 0;}}void md5_final(MD5_CTX *ctx, uint8_t hash[])uint32_t i = ctx->datalen;if (ctx->datalen < 56)ctx->data[i++] = 0x80;while (i < 56)ctx->data[i++] = 0x00;}} elsectx->data[i++] = 0x80;while (i < 64)ctx->data[i++] = 0x00;}md5_transform(ctx, ctx->data);memset(ctx->data, 0, 56);}ctx->bitlen[0] += ctx->datalen * 8;ctx->bitlen[1] += (ctx->bitlen[0] < ctx->datalen * 8); ctx->data[63] = ctx->bitlen[0] & 0xff;ctx->data[62] = (ctx->bitlen[0] >> 8) & 0xff;ctx->data[61] = (ctx->bitlen[0] >> 16) & 0xff;ctx->data[60] = (ctx->bitlen[0] >> 24) & 0xff;ctx->data[59] = ctx->bitlen[1] & 0xff;ctx->data[58] = (ctx->bitlen[1] >> 8) & 0xff;ctx->data[57] = (ctx->bitlen[1] >> 16) & 0xff;ctx->data[56] = (ctx->bitlen[1] >> 24) & 0xff;md5_transform(ctx, ctx->data);for (i = 0; i < 4; i++)hash[i] = (ctx->state[0] >> (i * 8)) & 0xff;hash[i + 4] = (ctx->state[1] >> (i * 8)) & 0xff;hash[i + 8] = (ctx->state[2] >> (i * 8)) & 0xff;hash[i + 12] = (ctx->state[3] >> (i * 8)) & 0xff;}void md5_transform(MD5_CTX *ctx, uint8_t data[])uint32_t a, b, c, d, f, g, temp;uint32_t m[16], i, j;for (i = 0, j = 0; i < 16; i++, j += 4)m[i] = (data[j]) + (data[j + 1] << 8) + (data[j + 2] << 16) + (data[j + 3] << 24);}a = ctx->state[0];b = ctx->state[1];c = ctx->state[2];d = ctx->state[3];for (i = 0; i < 64; i++)if (i < 16)f=(b&c),((~b)&d);g=i;} else if (i < 32)f=(d&b),((~d)&c);g=(5*i+1)%16;} else if (i < 48)f=b^c^d;g=(3*i+5)%16;} elsef=c^(b,(~d));g=(7*i)%16;}temp = d;d=c;c=b;b = b + leftrotate((a + f + k[i] + m[g]), r[i]);a = temp;}ctx->state[0] += a;ctx->state[1] += b;ctx->state[2] += c;ctx->state[3] += d;```4.实现加密函数:最后,可以编写一个简单的调用MD5算法的加密函数。
JAVA生成MD5校验码及算法实现

JAVA生成MD5校验码及算法实现在Java中,java.security.MessageDigest (rt.jar中)已经定义了MD5 的计算,所以我们只需要简单地调用即可得到MD5 的128 位整数。
然后将此128 位计16 个字节转换成16 进制表示即可。
下面是一个可生成字符串或文件MD5校验码的例子,测试过,可当做工具类直接使用,其中最主要的是getMD5String(String s)和getFileMD5String(File file)两个方法,分别用于生成字符串的md5校验值和生成文件的md5校验值,getFileMD5String_old(File file)方法可删除,不建议使用:package com.why.md5;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5Util {/*** 默认的密码字符串组合,用来将字节转换成16 进制表示的字符,apache 校验下载的文件的正确性用的就是默认的这个组合*/protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };protected static MessageDigest messagedigest = null;static {try {messagedigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException nsaex) {System.err.println(MD5Util.class.getName()+ "初始化失败,MessageDigest不支持MD5Util。
C语言实现MD5算法

C语言实现MD5算法MD5(Message-Digest Algorithm 5)是一种常用的哈希函数算法,广泛用于验证数据完整性、密码存储和数字证书等领域。
下面是使用C语言实现MD5算法的代码。
这段代码包含了MD5算法的各个步骤,包括初始化MD5结构体、填充数据、更新状态、计算摘要等。
```c#include <stdio.h>#include <stdint.h>#include <string.h>//定义MD5常量#define B 0xEFCDAB89#define C 0x98BADCFE//循环左移宏定义#define LEFT_ROTATE(x, n) (((x) << (n)) , ((x) >> (32-(n)))) //填充消息void padMessage(uint8_t *message, uint32_t length)//计算需要填充的字节数uint32_t padLength = (length % sizeof(uint32_t) == 56) ? 64 : 56;padLength = padLength - (length % sizeof(uint32_t));//填充1位1message[length++] = 0x80;//填充0位for (uint32_t i = 0; i < padLength; i++) message[length++] = 0x00;}//在消息末尾添加原始消息的长度(以位表示)for (uint32_t i = 0; i < sizeof(uint32_t); i++) message[length++] = (length << 3) >> (i * 8); }//初始化MD5结构体void initMD5(uint32_t *state)state[0] = A;state[1] = B;state[2] = C;state[3] = D;//更新状态void updateState(uint32_t *state, uint32_t *M)uint32_t A = state[0], B = state[1], C = state[2], D = state[3];//定义MD5循环运算函数#define MD5_FUNCTION(a, b, c, d, k, s, i) \a=b+LEFT_ROTATE((a+F(b,c,d)+M[k]+T[i]),s)//迭代压缩消息MD5_FUNCTION(A,B,C,D,0,7,1);MD5_FUNCTION(D,A,B,C,1,12,2);MD5_FUNCTION(C,D,A,B,2,17,3);MD5_FUNCTION(B,C,D,A,3,22,4);MD5_FUNCTION(A,B,C,D,4,7,5);MD5_FUNCTION(D,A,B,C,5,12,6);MD5_FUNCTION(C,D,A,B,6,17,7);MD5_FUNCTION(B,C,D,A,7,22,8);MD5_FUNCTION(A,B,C,D,8,7,9);MD5_FUNCTION(D,A,B,C,9,12,10);MD5_FUNCTION(C,D,A,B,10,17,11);MD5_FUNCTION(B,C,D,A,11,22,12);MD5_FUNCTION(A,B,C,D,12,7,13);MD5_FUNCTION(C,D,A,B,14,17,15); MD5_FUNCTION(B,C,D,A,15,22,16); MD5_FUNCTION(A,B,C,D,1,5,17); MD5_FUNCTION(D,A,B,C,6,9,18); MD5_FUNCTION(C,D,A,B,11,14,19); MD5_FUNCTION(B,C,D,A,0,20,20); MD5_FUNCTION(A,B,C,D,5,5,21); MD5_FUNCTION(D,A,B,C,10,9,22); MD5_FUNCTION(C,D,A,B,15,14,23); MD5_FUNCTION(B,C,D,A,4,20,24); MD5_FUNCTION(A,B,C,D,9,5,25); MD5_FUNCTION(D,A,B,C,14,9,26); MD5_FUNCTION(C,D,A,B,3,14,27); MD5_FUNCTION(B,C,D,A,8,20,28); MD5_FUNCTION(A,B,C,D,13,5,29); MD5_FUNCTION(D,A,B,C,2,9,30); MD5_FUNCTION(C,D,A,B,7,14,31); MD5_FUNCTION(B,C,D,A,12,20,32);MD5_FUNCTION(D,A,B,C,8,11,34); MD5_FUNCTION(C,D,A,B,11,16,35); MD5_FUNCTION(B,C,D,A,14,23,36); MD5_FUNCTION(A,B,C,D,1,4,37); MD5_FUNCTION(D,A,B,C,4,11,38); MD5_FUNCTION(C,D,A,B,7,16,39); MD5_FUNCTION(B,C,D,A,10,23,40); MD5_FUNCTION(A,B,C,D,13,4,41); MD5_FUNCTION(D,A,B,C,0,11,42); MD5_FUNCTION(C,D,A,B,3,16,43); MD5_FUNCTION(B,C,D,A,6,23,44); MD5_FUNCTION(A,B,C,D,9,4,45); MD5_FUNCTION(D,A,B,C,12,11,46); MD5_FUNCTION(C,D,A,B,15,16,47); MD5_FUNCTION(B,C,D,A,2,23,48); MD5_FUNCTION(A,B,C,D,0,6,49); MD5_FUNCTION(D,A,B,C,7,10,50); MD5_FUNCTION(C,D,A,B,14,15,51);MD5_FUNCTION(A,B,C,D,12,6,53); MD5_FUNCTION(D,A,B,C,3,10,54); MD5_FUNCTION(C,D,A,B,10,15,55); MD5_FUNCTION(B,C,D,A,1,21,56); MD5_FUNCTION(A,B,C,D,8,6,57); MD5_FUNCTION(D,A,B,C,15,10,58); MD5_FUNCTION(C,D,A,B,6,15,59); MD5_FUNCTION(B,C,D,A,13,21,60); MD5_FUNCTION(A,B,C,D,4,6,61); MD5_FUNCTION(D,A,B,C,11,10,62); MD5_FUNCTION(C,D,A,B,2,15,63); MD5_FUNCTION(B,C,D,A,9,21,64); #undef MD5_FUNCTION//更新状态state[0] += A;state[1] += B;state[2] += C;state[3] += D;//计算MD5摘要void md5(uint8_t *message, uint32_t length, uint32_t *digest) //初始化MD5结构体uint32_t state[4];initMD5(state);//填充消息padMessage(message, length);//计算消息分组数量uint32_t numOfBlocks = length / 64;//处理每个分组for (uint32_t i = 0; i < numOfBlocks; i++)uint32_t M[16];memcpy(M, message + (i * 64), 64);//更新状态updateState(state, M);}//获取MD5摘要memcpy(digest, state, 16);int mai//测试用例uint8_t message[] = "Hello, MD5!";uint32_t length = sizeof(message) - 1;//计算MD5摘要uint32_t digest[4];md5(message, length, digest);//输出摘要printf("MD5 Digest: ");for (int i = 0; i < 4; i++)printf("%02x", ((uint8_t*)digest)[i]);}printf("\n");return 0;```以上是使用C语言实现MD5算法的代码。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//以下为md5计算程序源代码,可以复制到自己的程序中使用,使用方法见最后的main函数//经测试,绝对可以使用//////////////////////////////////////////////////////#include <iostream>#include <string>#include <fstream>using namespace std;/* 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 };};/* 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) { \(a) += G ((b), (c), (d)) + (x) + ac; \(a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}#define HH(a, b, c, d, x, s, ac) { \(a) += H ((b), (c), (d)) + (x) + ac; \(a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}#define II(a, b, c, d, x, s, ac) { \(a) += I ((b), (c), (d)) + (x) + ac; \(a) = ROTATE_LEFT ((a), (s)); \(a) += (b); \}const byte MD5::PADDING[64] = { 0x80 };const char MD5::HEX[16] = {'0', '1', '2', '3','4', '5', '6', '7','8', '9', 'a', 'b','c', 'd', 'e', 'f'};/* Default construct. */MD5::MD5() {reset();}/* Construct a MD5 object with a input buffer. */MD5::MD5(const void* input, size_t length) {reset();update(input, length);}/* Construct a MD5 object with a string. */MD5::MD5(const string& str) {reset();update(str);}/* Construct a MD5 object with a file. */MD5::MD5(ifstream& in) {reset();update(in);}/* Return the message-digest */const byte* MD5::digest() {if (!_finished) {_finished = true;final();}return _digest;}/* Reset the calculate state */void MD5::reset() {_finished = false;/* reset number of bits. */_count[0] = _count[1] = 0;/* Load magic initialization constants. */_state[0] = 0x67452301;_state[1] = 0xefcdab89;_state[2] = 0x98badcfe;_state[3] = 0x10325476;}/* Updating the context with a input buffer. */void MD5::update(const void* input, size_t length) { update((const byte*)input, length);}/* Updating the context with a string. */void MD5::update(const string& str) {update((const byte*)str.c_str(), str.length());/* Updating the context with a file. */void MD5::update(ifstream& in) {if (!in) {return;}std::streamsize length;char buffer[BUFFER_SIZE];while (!in.eof()) {in.read(buffer, BUFFER_SIZE);length = in.gcount();if (length > 0) {update(buffer, length);}}in.close();}/* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context.*/void MD5::update(const byte* input, size_t length) {uint32 i, index, partLen;_finished = false;/* Compute number of bytes mod 64 */index = (uint32)((_count[0] >> 3) & 0x3f);/* update number of bits */if ((_count[0] += ((uint32)length << 3)) < ((uint32)length << 3)) { ++_count[1];}_count[1] += ((uint32)length >> 29);partLen = 64 - index;/* transform as many times as possible. */if (length >= partLen) {memcpy(&_buffer[index], input, partLen);transform(_buffer);for (i = partLen; i + 63 < length; i += 64) {transform(&input[i]);}index = 0;} else {i = 0;}/* Buffer remaining input */memcpy(&_buffer[index], &input[i], length - i);}/* MD5 finalization. Ends an MD5 message-_digest operation, writing the the message _digest and zeroizing the context.*/void MD5::final() {byte bits[8];uint32 oldState[4];uint32 oldCount[2];uint32 index, padLen;/* Save current state and count. */memcpy(oldState, _state, 16);memcpy(oldCount, _count, 8);/* Save number of bits */encode(_count, bits, 8);/* Pad out to 56 mod 64. */index = (uint32)((_count[0] >> 3) & 0x3f);padLen = (index < 56) ? (56 - index) : (120 - index);update(PADDING, padLen);/* Append length (before padding) */update(bits, 8);/* Store state in digest */encode(_state, _digest, 16);/* Restore current state and count. */memcpy(_state, oldState, 16);memcpy(_count, oldCount, 8);}/* MD5 basic transformation. Transforms _state based on block. */ void MD5::transform(const byte block[64]) {uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16];decode(block, x, 64);/* Round 1 */FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 *//* Round 2 */GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 *//* Round 3 */HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 *//* Round 4 */II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */_state[0] += a;_state[1] += b;_state[2] += c;_state[3] += d;}/* Encodes input (ulong) into output (byte). Assumes length isa multiple of 4.*/void MD5::encode(const uint32* input, byte* output, size_t length) {for (size_t i = 0, j = 0; j < length; ++i, j += 4) {output[j]= (byte)(input[i] & 0xff);output[j + 1] = (byte)((input[i] >> 8) & 0xff);output[j + 2] = (byte)((input[i] >> 16) & 0xff);output[j + 3] = (byte)((input[i] >> 24) & 0xff);}}/* Decodes input (byte) into output (ulong). Assumes length isa multiple of 4.*/void MD5::decode(const byte* input, uint32* output, size_t length) {for (size_t i = 0, j = 0; j < length; ++i, j += 4) {output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) | (((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24);}}/* Convert byte array to hex string. */string MD5::bytesToHexString(const byte* input, size_t length) {string str;str.reserve(length << 1);for (size_t i = 0; i < length; ++i) {int t = input[i];int a = t / 16;int b = t % 16;str.append(1, HEX[a]);str.append(1, HEX[b]);}return str;}/* Convert digest to string value */string MD5::toString() {return bytesToHexString(digest(), 16);}void PrintMD5(const string& str, MD5& md5) {cout << "MD5(\"" << str << "\") = " << md5.toString() << endl;}string FileDigest(const string& file) {ifstream in(file.c_str(), ios::binary);if (!in) {return "";}MD5 md5;std::streamsize length;char buffer[1024];while (!in.eof()) {in.read(buffer, 1024);length = in.gcount();if (length > 0) {md5.update(buffer, length);}}in.close();return md5.toString();}int main() {//cout << MD5("abc").toString() << endl;//cout << MD5(ifstream("D:\test.txt")).toString() << endl;//cout << MD5(ifstream("D:\test.exe", ios::binary)).toString() << endl; //cout << FileDigest("D:\test.exe") << endl;MD5 md5;md5.update("");PrintMD5("", md5);md5.update("a");PrintMD5("a", md5);md5.update("bc");PrintMD5("abc", md5);md5.update("defghijklmnopqrstuvwxyz"); PrintMD5("abcdefghijklmnopqrstuvwxyz", md5);md5.reset();md5.update("message digest");PrintMD5("message digest", md5);//md5.reset();//md5.update(ifstream("D:\test.txt"));//PrintMD5("D:\test.txt", md5);return 0;}。