2 回答

TA貢獻1946條經驗 獲得超3個贊
在SQL Server 2005下自帶的函數HashBytes() ,此函數是微軟在SQL Server 2005中提供的,可以用來計算一個字符串的MD5和SHA1值,使用方法如下:
--獲取123456的MD5加密串
select hashbytes('MD5', '123456') ;
--獲取123456的SHA1加密串
select hashbytes('SHA1', '123456') ;
有了這個函數可以在SQL Server中為字符串進行加密,但是HashBytes() 函數的返回結果是VarBinary類型(以 0x 開頭 16 進制形式的二進制數據)。通常情況下,我們需要的都是字符串型的數據,很多人首先想到的可能就是用CAST或Convert函數將VarBinary轉換為VarChar,但這樣轉換后的結果會是亂碼,正確轉換VarBinary可變長度二進制型數據到16進制字符串應該使用系統內置函數sys.fn_VarBinToHexStr()或sys.fn_SqlVarBaseToStr(只在sqlserver2005以后的有),如下所示:
select sys.fn_VarBinToHexStr(hashbytes('MD5', '123456'))
然后就可以截取需要的部分:
set right(sys.fn_VarBinToHexStr(hashbytes('MD5','123456')),32)
為MD5加密串。

TA貢獻2016條經驗 獲得超9個贊
剛好今天找到的:怎么用,你應該知道了吧?
public string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
- 2 回答
- 0 關注
- 1028 瀏覽
添加回答
舉報