Java和C#的Hash算法的方法介绍
由于Hash算法返回的是byte数组,为了显示数据,将byte数组转换成Base64字符串。
Java中使用Hash算法:
import java.security.*;
public static String HashBase64(String str)
{ String ret=""; try { //Hash算法 MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(str.getBytes()); ret=new sun.misc.BASE64Encoder().encode(sha.digest()); } catch (Exception e) { System.out.print(e.getMessage()); } return ret; }C#使用Hash算法:
using System.Security.Cryptography;
public static string HashBase64(string str)
{ byte[] result = new byte[str.Length]; try { SHA1 sha = new SHA1CryptoServiceProvider(); result = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str)); return Convert.ToBase64String(result); } catch { return ""; } }