签名算法,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;
}
c#

4个回答

已经解决,代码如下:
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);
        }

c#也有 URLEncoder,StringBuilder

Convert.ToString(intA, 16),把数字转为16进制

private static final String HASH = "HmacSHA256";

没有会的吗?
需要一个完整的代码,thx!!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐