Java计算文本MD5加密值的方法示例

时间:2022-12-05 07:35:47

本文实例讲述了java计算文本md5加密值的方法。分享给大家供大家参考,具体如下:

java计算文本md5值,用于加密

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
public class getmd5 {
  public static void main(string[] args) {
    string a="123";
  system.out.println(getmd5(a));
  }
  /**
   * 获取文本字段的md5值
   * @param txt
   * @return
   */
  public static string getmd5(string txt){
    string rs = "";
    string[] hexdigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8","9", "a", "b", "c", "d", "e", "f" };
    try {
      messagedigest messagedigest = messagedigest.getinstance("md5");
      byte[] b = messagedigest.digest(txt.getbytes());
      stringbuffer resultsb = new stringbuffer();
      for (int i = 0; i < b.length; i++) {
        int n = b[i];
        if (n < 0)
          n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        resultsb.append(hexdigits[d1] + hexdigits[d2]);
      }
      rs = resultsb.tostring();
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    }
    return rs;
  }
}

输出值:

202cb962ac59075b964b07152d234b70

ps:关于加密解密感兴趣的朋友还可以参考本站在线工具:

文字在线加密解密工具(包含aes、des、rc4等):https://tool.zzvips.com/t/txt_encode/

md5在线加密工具:https://tool.zzvips.com/t/md5/

在线sha1/sha224/sha256/sha384/sha512加密工具:https://tool.zzvips.com/t/sha/

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/u013183865/article/details/50595746