Every day is wonderful

分享与创新 并大胆的去尝试新鲜事物。。。。

一个简单的MD5生成方法

JAVA代码

public static String createMD5(String src) throws NoSuchAlgorithmException, UnsupportedEncodingException {
String result=””;
if(src!=null) {
MessageDigest md=MessageDigest.getInstance(“MD5”);
md.update(src.getBytes(“UTF-8”));
byte messageDigest[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0;i String hex = Integer.toHexString(0xFF & messageDigest[i]);
hexString.append(hex.length()<2 ? "0"+hex : hex);
}
result=hexString.toString().toUpperCase();
}
return result;
}


环境:vs.net2005/sql server2000/xp测试通过

1.MD5 16位加密实例
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace md5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(UserMd5(\”8\”));
Console.WriteLine(GetMd5Str(\”8\”));
}
/**////

/// MD5 16位加密
///

/// ///
public static string GetMd5Str(string ConvertString)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
t2 = t2.Replace(\”-\”, \”\”);
return t2;
}
/**////

/// MD5 32位加密
///

/// ///
static string UserMd5(string str)
{
string cl = str;
string pwd = \”\”;
MD5 md5 = MD5.Create();//实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i < s.Length; i )
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符

pwd = pwd s[i].ToString(\”X\”);

}
return pwd;
}
}
}

简单法(未测试)


public static string MD5(string Sourcein)
{
MD5CryptoServiceProvider MD5CSP = new MD5CryptoServiceProvider();
byte[] MD5Source = System.Text.Encoding.UTF8.GetBytes(Sourcein);
byte[] MD5Out = MD5CSP.ComputeHash(MD5Source);
return Convert.ToBase64String(MD5Out);
}

点赞

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注