芝麻_糊

导航

数字签名-MD5

MD5是信息摘要的意思,报文产生摘要是唯一的(1:1),而且是单向的(通过摘要反推不出源报文)

java中的java.security.MessageDigest类,参考MessageDigest的功能及用法

 1  public static byte[] getMD5Mac(byte[] bySourceByte) {
 2         byte[] byDisByte;
 3         MessageDigest md;
 4         try {
 5             md = MessageDigest.getInstance("MD5");
 6             md.reset();
 7             md.update(bySourceByte);
 8             byDisByte = md.digest();
 9         } catch (NoSuchAlgorithmException n) {
10             return (null);
11         }
12         return (byDisByte);
13     }

MessageDigest 是 statefull,电话 MessageDigest.update (byte [] 输入) 累积文摘更新,直到我们称之为 MessageDigest.digest。运行此测试,以确保:

   
1     MessageDigest md1 = MessageDigest.getInstance("MD5");
2     md1.update(new byte[] {1, 2});
3     md1.update(new byte[] {3, 4});
4     System.out.println(Arrays.toString(md1.digest()));
5 
6     MessageDigest md2 = MessageDigest.getInstance("MD5");
7     md2.update(new byte[] {1, 2, 3, 4});
8     System.out.println(Arrays.toString(md2.digest()));
输出:
[8, -42, -64, 90, 33, 81, 42, 121, -95, -33, -21, -99, 42, -113, 38, 47]
[8, -42, -64, 90, 33, 81, 42, 121, -95, -33, -21, -99, 42, -113, 38, 47]

生成的摘要是byte[]类型的,需要转换成String

 1 public static String bintoascii(byte[] bySourceByte) {
 2         int len, i;
 3         byte tb;
 4         char high, tmp, low;
 5         len = bySourceByte.length;
 6         StringBuilder sb = new StringBuilder(len);
 7         for (i = 0; i < len; i++) {
 8             tb = bySourceByte[i];
 9             tmp = (char) ((tb >>> 4) & 0x000f);
10             if (tmp >= 10)
11                 high = (char) ('a' + tmp - 10);
12             else
13                 high = (char) ('0' + tmp);
14             sb.append(high);
15             tmp = (char) (tb & 0x000f);
16             if (tmp >= 10)
17                 low = (char) ('a' + tmp - 10);
18             else
19                 low = (char) ('0' + tmp);
20             sb.append(low);
21         }
22         return sb.toString();
23     }

 

posted on 2017-10-08 16:10  芝麻_糊  阅读(885)  评论(0编辑  收藏  举报