Java和C#的Hash算法

来源:互联网 发布:淘宝宝贝图片最佳尺寸 编辑:程序博客网 时间:2024/04/25 06:36

由于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 "";
  }    

原创粉丝点击