carson1978
carson1978
采纳率100%
2015-05-14 08:53 阅读 2.0k

签名算法,java代码转为 C#

2

请帮忙把如下的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;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    carson1978 carson1978 2015-05-15 02:11

    已经解决,代码如下:
    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);
            }
    
    点赞 评论 复制链接分享
  • bdmh bdmh 2015-05-14 09:03

    c#也有 URLEncoder,StringBuilder

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

    点赞 评论 复制链接分享
  • carson1978 carson1978 2015-05-14 09:25

    private static final String HASH = "HmacSHA256";

    点赞 评论 复制链接分享
  • carson1978 carson1978 2015-05-15 01:14

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

    点赞 评论 复制链接分享

相关推荐