Java 和 .NET SHA1算法记录

  最近做了一个.NET访问Java接口的小Demo,其中用到了SHA1加密,大体思路就是.NET 传一些参数然后SHA1加密,Java端接收到之后在SHA1加密对比。

  Java代码:

  

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
35
36
37
38
public final class SHA1 {
        private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
                '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
        /**
         * Takes the raw bytes from the digest and formats them correct.
         *
         * @param bytes the raw bytes from the digest.
         * @return the formatted bytes.
         */
        private static String getFormattedText(byte[] bytes) {
            int len = bytes.length;
            StringBuilder buf = new StringBuilder(len * 2);
            // 把密文转换成十六进制的字符串形式
            for (int j = 0; j < len; j++) {
                buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
                buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
            }
            return buf.toString();
        }
 
        /**
         * 编码
         * */
        public static String encode(String str) {
            if (str == null) {
                return null;
            }
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
                messageDigest.update(str.getBytes());
                return getFormattedText(messageDigest.digest());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
 
}

  .NET代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public  string SHA1(string content, Encoding encode)
      {
          try
          {
              SHA1 sha1 = new SHA1CryptoServiceProvider();
              byte[] bytes_in = encode.GetBytes(content);
              byte[] bytes_out = sha1.ComputeHash(bytes_in);
              sha1.Dispose();
              StringBuilder ret = new StringBuilder();
              foreach (byte b in bytes_out)
              {
                  //{0:X2} 大写
                  ret.AppendFormat("{0:x2}", b);
              }
              var hex = ret.ToString();
              return hex;
          }
          catch (Exception ex)
          {
              throw new Exception("SHA1加密出错:" + ex.Message);
          }
      }

  经测试,两种加密方法得到的结果是一致的~~

posted @   丶Pz  阅读(393)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示