美文网首页Java专题
微信两种签名算法MD5和HMAC-SHA256

微信两种签名算法MD5和HMAC-SHA256

作者: 愤怒的小菜鸡 | 来源:发表于2019-08-07 00:13 被阅读0次

    在做微信接口开发的过程中, 有时候发现会提示签名校验失败, 一模一样的签名逻辑就是有些接口跑步通, 找了一圈发现挺坑的;

    原来是有些接口的signType签名类型有区别, 有些接口signType要求是MD5,有的要求是HMAC-SHA256, 其实这两种算法都是

    hash算法的一种没有太大的差别, 但是生成的签名结果会不一样;

    下面附上HMAC-SHA256算法代码

    package com.lh.micro.datasource.util;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    
    public class HMACSHA256 {
    
    
        /**
         * 将加密后的字节数组转换成字符串
         *
         * @param b 字节数组
         * @return 字符串
         */
        public  static String byteArrayToHexString(byte[] b) {
            StringBuilder hs = new StringBuilder();
            String stmp;
            for (int n = 0; b!=null && n < b.length; n++) {
                stmp = Integer.toHexString(b[n] & 0XFF);
                if (stmp.length() == 1)
                    hs.append('0');
                hs.append(stmp);
            }
            return hs.toString().toLowerCase();
        }
        /**
         * sha256_HMAC加密
         * @param message 消息
         * @param secret  秘钥
         * @return 加密后字符串
         */
        public static String sha256_HMAC(String message, String secret) {
            String hash = "";
            try {
                Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
                SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
                sha256_HMAC.init(secret_key);
                byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
                hash = byteArrayToHexString(bytes);
            } catch (Exception e) {
                System.out.println("Error HmacSHA256 ===========" + e.getMessage());
            }
            return hash;
        }
    
    
    }
    

    历史文章:
    JAVA微信企业付款到零钱(十分钟搞定)
    微信授权获取用户openId的方法和步骤
    一个微信号同时支持多个环境网页授权
    微信两种签名算法MD5和HMAC-SHA256

    相关文章

      网友评论

        本文标题:微信两种签名算法MD5和HMAC-SHA256

        本文链接:https://www.haomeiwen.com/subject/gfxndctx.html