API接口加密方式代码分享API接口加密源代码JAVA版

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版本代码编写感谢袁敏老师的支持,欢迎大家多多技术交流

原文地址:https://www.cnblogs.com/keleyu/p/13644910.html