钉钉JsApi签名工具类JsApiSign

钉钉jsapi签名工具类

/**
 * Created by xiangYang on 2017/4/26.
 */
import com.maycur.dingtalk.dto.JsApiSignatureDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JsApiSign {
    private static final Logger logger = LoggerFactory.getLogger(JsApiSign.class);

    public static JsApiSignatureDto  getSignature(String jsapiTicket, String url) {
        logger.info("getSignature jsapiTicket:{" + jsapiTicket + "} {url:" + url + "}");
        JsApiSignatureDto ret = dingTalkSign(jsapiTicket, url);
        return ret;

    }

    private static JsApiSignatureDto dingTalkSign(String jsApiTicket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        JsApiSignatureDto jsApiSignatureDto = new JsApiSignatureDto();

        String nonceStr = create_nonce_str();
        String timestamp = create_timestamp();
        String plain = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "&timestamp="
                + timestamp + "&url=" + url;
        String signature = "";
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.reset();
            sha1.update(plain.getBytes("UTF-8"));
            signature = byteToHex(sha1.digest());
            jsApiSignatureDto.setUrl(url);
            jsApiSignatureDto.setJsApiTicket(jsApiTicket);
            jsApiSignatureDto.setTimestamp(Long.valueOf(timestamp));
            jsApiSignatureDto.setNonceStr(nonceStr);
            jsApiSignatureDto.setSignatureStr(signature);
        } catch (NoSuchAlgorithmException e) {
            logger.error("sign essro" + e);
        } catch (UnsupportedEncodingException e) {
            logger.error("sign essro" + e);

        }

        return jsApiSignatureDto;
    }

    private static String byteToHex(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 create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值