从字符串计算MD5哈希 [英] calculate a MD5 hash from a string

查看:145
本文介绍了从字符串计算MD5哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的C#code从字符串计算MD5哈希值。
它运作良好,并产生一个32字符的十六进制字符串是这样的:
900150983cd24fb0d6963f7d28e17f72

 字符串sSourceData;
字节[] tmpSource;
字节[] tmpHash;
sSourceData =MySourceData;
//创建一个从源数据的字节数组。
tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
tmpHash =新MD5CryptoServiceProvider()ComputeHash(tmpSource)。
//然后转换tmpHash串...

有没有办法使用code这样生成一个16字符的十六进制字符串(或12个字符的字符串)? 32个字符的十六进制字符串是好的,但我认为这将是枯燥为客户输入code!


解决方案

  //给出字符串中的密码
字符串密码= @1234ABCD//字节数组再该字符串的presentation
。字节[] EN codedPassword =新UTF8Encoding()GetBytes会(密码);//需要MD5计算哈希
字节[]哈希=((的HashAlgorithm)CryptoConfig.CreateFromName(MD5))ComputeHash(EN codedPassword)。//字符串重新presentation(类似于UNIX格式)
字符串连接codeD = BitConverter.ToString(散)
   //没有破折号
   .Replace( - ,的String.Empty)
   //变为小写
   。降低();// EN codeD中包含你想要的哈希

I use the following C# code to calculate a MD5 hash from a string. It works well and generates a 32-character hex string like this: 900150983cd24fb0d6963f7d28e17f72

string sSourceData;
byte[] tmpSource;
byte[] tmpHash;
sSourceData = "MySourceData";
//Create a byte array from source data.
tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
// and then convert tmpHash to string...

Is there any way to use code like this to generate a 16-character hex string (or 12-character string)? A 32-character hex string is good but I think it'll be boring for the customer to enter the code!

解决方案

// given, a password in a string
string password = @"1234abcd";

// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);

// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);

// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
   // without dashes
   .Replace("-", string.Empty)
   // make lowercase
   .ToLower();

// encoded contains the hash you are wanting

这篇关于从字符串计算MD5哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆