钉钉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 + "×tamp="
+ 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);
}
}