Java tutorial
package com.javaps.springboot; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class LicenseController { @Value("${config.licenseSecretKey}") private String licenseSecretKey; @RequestMapping(value = "/public/license", produces = "text/plain", method = RequestMethod.POST) public String licenseValidate(HttpServletRequest req, @RequestBody String license) throws Exception { String clientIp = req.getHeader("X-Forwarded-For"); //nginx???IP if (clientIp == null) clientIp = req.getRemoteAddr(); //????? //System.out.println("clientIp="+clientIp); SecretKeySpec signingKey = new SecretKeySpec(licenseSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(clientIp.getBytes()); //System.out.println("license should be:"+Base64.encodeBase64String(rawHmac)); if (!license.equals(Base64.encodeBase64String(rawHmac))) throw new Exception(); return "OK"; } @RequestMapping(value = "/public/license", produces = "text/plain", method = RequestMethod.GET) public String licenseIssue(@RequestParam(value = "ip") String clientIp) throws Exception { SecretKeySpec signingKey = new SecretKeySpec(licenseSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(clientIp.getBytes()); return Base64.encodeBase64String(rawHmac); } }