程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> java c# sign-簽名算法,java代碼轉為 C#

java c# sign-簽名算法,java代碼轉為 C#

編輯:編程綜合問答
簽名算法,java代碼轉為 C#

請幫忙把如下的java簽名算法轉換為c#的,牛人伸手啊!!

具體代碼如下:
public static String genSignature(String sk, String stringToSign) {
String signature = "";

    try {
        String encodedSign = URLEncoder.encode(stringToSign, ENCODING);
        try {
            Mac mac = Mac.getInstance(HASH);
            mac.init(new SecretKeySpec(sk.getBytes(ENCODING), HASH));
            byte[] hashData = mac.doFinal(encodedSign.getBytes(ENCODING));

            StringBuilder sb = new StringBuilder(hashData.length * 2);
            for (byte data : hashData) {
                String hex = Integer.toHexString(data & 0xFF);
                if (hex.length() == 1) {
                    // append leading zero
                    sb.append("0");
                }
                sb.append(hex);
            }
            signature = sb.toString().toLowerCase();
        } catch (Exception e) {
            logger.warn("sha256 exception for[" + sk + "," + stringToSign + "]. e:", e);
        }
    } catch (UnsupportedEncodingException e) {
        logger.warn("encode error, string[" + stringToSign + "] e:" + e);
    }

    return signature;
}

最佳回答:


已經解決,代碼如下:
public static string genSignature(string sk,string data)
{
UTF8Encoding enc = new UTF8Encoding();
byte[] secretKey = enc.GetBytes(sk);
HMACSHA256 hmac = new HMACSHA256(secretKey);
hmac.Initialize();

        byte[] bytes = enc.GetBytes(data);
        byte[] hashBytes = hmac.ComputeHash(bytes);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < hashBytes.Length; i++)
        {
            string hex = (hashBytes[i] & 0xFF).ToString("x");
            if (hex.Length == 1)
            {
                sb.Append("0");
            }
            sb.Append(hex);
        }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved