Java 和 .NET SHA1演算法記錄

丶Pz發表於2018-04-20

  最近做了一個.NET訪問Java介面的小Demo,其中用到了SHA1加密,大體思路就是.NET 傳一些引數然後SHA1加密,Java端接收到之後在SHA1加密對比。

  Java程式碼:

  

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程式碼

  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);
            }
        }

  經測試,兩種加密方法得到的結果是一致的~~

相關文章