JAVA:MD5-MD2計算

private static void MD5(){
try {
// 獲取MD5加密工具
MessageDigest md = MessageDigest.getInstance("MD5");
// 加密
byte[] digest = md.digest(mStr.getBytes());
for (byte b : digest) {
System.out.println(b);
}
// 獲取二進制十六進制互轉工具
HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter();
// 將二進制數組轉換爲十六進制字符串
String marshal = hexBinaryAdapter.marshal(digest);
// 輸出結果
System.out.println(marshal);
} catch (Exception e) {
e.printStackTrace();
}
}

private static void MD2(){
try {
// 獲取MD2加密工具
MessageDigest md = MessageDigest.getInstance("MD2");
// 加密
byte[] digest = md.digest(mStr.getBytes());
for (byte b : digest) {
System.out.println(b);
}
// 獲取二進制十六進制互轉工具
HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter();
// 將二進制數組轉換爲十六進制字符串
String marshal = hexBinaryAdapter.marshal(digest);
// 輸出結果
System.out.println(marshal);
} catch (Exception e) {
e.printStackTrace();
}
}

網絡搜索:

1、計算字符串的MD5值

public string GetMD5WithString(string sDataIn)
{
    string str = "";
    byte[] data = Encoding.GetEncoding("utf-8").GetBytes(str);
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] bytes = md5.ComputeHash(data);
    for (int i = 0; i < bytes.Length; i++)
    {
        str += bytes[i].ToString("x2");
    }
    return str;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2、計算文件的MD5值

public string GetMD5WithFilePath(string filePath)
{
    FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] hash_byte = md5.ComputeHash(file);
    string str = System.BitConverter.ToString(hash_byte);
    str = str.Replace("-", "");
    return str;
}
發佈了30 篇原創文章 · 獲贊 34 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章