API接口加密方式代碼分享API接口加密源代碼JAVA版,一下是JAVA完整的加密源代碼,含有服務端和客戶端demo
我之前寫好了一版PHP版本的API接口加密通信DEMO代碼
現在這一版是JAVA版API接口加密通信代碼,並且這一版的客戶端Test.java和我寫好的PHP服務端是完全互通的
當然下面寫好的服務端Encry.java和之前的寫的PHP客戶端也是互通的,這樣做也是為了讓同時有JAVA和PHP的程序員們能更好地協作通信
1.加密簽名類EncryBean.java
2.服務端:Encry.java
3.客戶端:Test.java
這和我之前寫好的PHP服務端代碼是互通的,這樣子也方便用JAVA的小白盡快上手
以下是JAVA版的API接口加密通信源代碼,代碼含客戶端和服務端
1.EncryBean.java是封裝的加密生成簽名的類文件
package bean; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class EncryBean { public String timeStamp;//時間戳 public String randomStr;//隨機串 public String signature;//簽名 public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public String getRandomStr() { return randomStr; } public void setRandomStr(String randomStr) { this.randomStr = randomStr; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public EncryBean() { } public EncryBean(String timeStamp, String randomStr, String signature) { super(); this.timeStamp = timeStamp; this.randomStr = randomStr; this.signature = signature; } /** * @param timeStamp 時間戳 * @param randomStr 隨機字符串 * @param tk 令牌字符串 * @return string 返回簽名 */ @SuppressWarnings("static-access") public String arithmetic(String timeStamp,String randomStr,String tk){ String [] arr = new String[3]; arr[0] = timeStamp; arr[1] = tk; arr[2] = randomStr; StringBuilder bf = new StringBuilder(); for(int i =0; i<arr.length;i++){ bf.append(arr[i]);//按照首字母大小寫順序排序 拼接成字符串 } String signature=""; try { signature = this.shaEncode(bf.toString()); } catch (Exception e) { e.printStackTrace(); }//SHA-1加密 signature = this.encryption(signature);//MD5加密 return signature.toUpperCase();//轉成大寫字符 } /** * @Comment SHA1實現 */ public static String shaEncode(String inStr) throws Exception { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); return ""; } byte[] byteArray = inStr.getBytes("UTF-8"); byte[] md5Bytes = sha.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } /** * @param Md5實現 */ public String encryption(String plainText) { String re_md5 = new String(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } re_md5 = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return re_md5; } }
2.服務端是Encry.java ,這個文件接收客戶端請求
package encry; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import bean.EncryBean; public class Encry extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); String timeStamp = request.getParameter("t");//獲取時間戳 String randomStr = request.getParameter("r");//獲取隨機串 String signature = request.getParameter("s");//獲取簽名 PrintWriter out = response.getWriter(); Map<String, Object> map = new HashMap<String, Object>(); if(timeStamp==null && timeStamp==""){ map.put("status", "100");//狀態碼100時間戳不能為空 } if(randomStr==null && randomStr==""){ map.put("status", "101");//狀態碼101隨機串不能為空 } if(signature==null && signature==""){ map.put("status", "102");//狀態碼102簽名不能為空 } System.out.println("timeStamp"+timeStamp); System.out.println("randomStr"+randomStr); System.out.println("signature"+signature); String TOKEN = "API";//令牌字符串(雙方約定) EncryBean a = new EncryBean(); String str = a.arithmetic(timeStamp,randomStr,TOKEN);//通過前台傳過來的時間戳跟隨機數重新按照簽名函數進行生成一遍簽名 //然后將傳過來簽名跟,自己重新生成的簽名進行比對 if(str.equals(signature)){ map.put("status", "1");//狀態碼1成功 }else{ map.put("status", "0");//狀態碼0簽名錯誤 } String mapJson = JSON.toJSONString(map); out.print(mapJson); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
3.客戶端調用是Test.java
package bean; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Test { public static String interfaceUtil(String path,String data) { StringBuilder sb = new StringBuilder(); try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET");//GET和POST必須全大寫 conn.connect(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = ""; while ((str = br.readLine()) != null) { str=new String(str.getBytes(),"UTF-8");//解決中文亂碼問題 sb.append(str); } is.close(); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } public static void main(String[] args) { String tk = "API";//密鑰 String t = System.currentTimeMillis()+"" ;//時間戳; String r = "zf4edLXLl666666666"; //隨機串 EncryBean a = new EncryBean(); String s = a.arithmetic(t,r,tk);//生成簽名 //String response = interfaceUtil("http://localhost:8080/servlet/Encry?t="+t+"&r="+r+"&s="+s,"");//get請求 String response = interfaceUtil("http://www.myhost.com/api.php?t="+t+"&r="+r+"&s="+s,"");//get請求 System.out.println(response); } }
以上就是JAVA版的API接口加密代碼,JAVA版本代碼編寫感謝袁敏老師的支持,歡迎大家多多技術交流