zoukankan      html  css  js  c++  java
  • 企业微信-签名算法

    package com.xc.xcspringboot.demo;
    
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Formatter;
    
    /**
     * https://work.weixin.qq.com/api/doc/90000/90136/90506
     *
     * @author tl19638
     * @date 2020/8/18
     */
    public class 签名算法 {
    
        public static void main(String[] args) throws Exception {
            String genNonce = genNonce();
            System.out.println("noncestr:" + genNonce);
    
            long timestamp = System.currentTimeMillis() / 1000;
            System.out.println("timestamp:" + timestamp);
    
            String sign = sign("https://www.sogou.com", genNonce, timestamp, "eaed581b260d754b1adf54d7875adc27");
            System.out.println("sign:" + sign);
        }
    
    
        /**
         * 模拟生成随机 nonce 字符串
         *
         * @return 随机字符串
         */
        private static String genNonce() {
            return bytesToHex(Long.toString(System.nanoTime()).getBytes(StandardCharsets.UTF_8));
        }
    
        private static String bytesToHex(final byte[] hash) {
            Formatter formatter = new Formatter();
            for (byte b : hash) {
                formatter.format("%02x", b);
            }
            String result = formatter.toString();
            formatter.close();
            return result;
        }
    
        private static String sign(String url, String nonce, Long timestamp, String ticket) throws Exception {
            String plain = String.format("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", ticket, nonce, timestamp, url);
            System.out.println("plain:" + plain);
            try {
                MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                sha1.reset();
                sha1.update(plain.getBytes(StandardCharsets.UTF_8));
                return bytesToHex(sha1.digest());
            } catch (NoSuchAlgorithmException e) {
                // throw new LeysenException("jsapi_ticket计算签名错误");
                throw new Exception("jsapi_ticket计算签名错误");
            }
        }
    
    
    }
  • 相关阅读:
    PAT 天梯赛 L2-003. 月饼 【贪心】
    PAT 天梯赛 L2-015. 互评成绩 【排序】
    PAT 天梯赛 L1-046. 整除光棍 【模拟除法】
    PAT 天梯赛 L1-006. 连续因子 【循环】
    PAT 天梯赛 L1-009. N个数求和 【模拟】
    HackerRank
    ZOJ 3961 Let's Chat 【水】
    ZOJ 3960 What Kind of Friends Are You? 【状态标记】
    ZOJ 3959 Problem Preparation 【水】
    ZOJ 3958 Cooking Competition 【水】
  • 原文地址:https://www.cnblogs.com/ooo0/p/13673907.html
Copyright © 2011-2022 走看看