RSA接口加密

1.工具类

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import javax.crypto.Cipher;

import org.apache.commons.lang3.ArrayUtils;
/**
 * Java RSA 加密工具类
 * 参考: https://blog.csdn.net/qy20115549/article/details/83105736
 */
public class RSAUtils {
    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 1024;
    /**
     * 用于封装随机产生的公钥与私钥
     */
//    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
    /**
     * 随机生成密钥对
     */
    public static List<String> genKeyPair() throws NoSuchAlgorithmException {
    	List<String> keyList = new ArrayList();
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        // 将公钥和私钥保存到Map
        //0表示公钥
        keyList.add(publicKeyString);
        //1表示私钥
        keyList.add(privateKeyString);
		return keyList;
    }
    
    
    
    
    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        
        byte[] bytes = str.getBytes("UTF-8");
        byte[] dataReturn = {};
        // 加密时超过117字节就报错。为此采用分段加密的办法来加密
     			StringBuilder sb = new StringBuilder();
     			for (int i = 0; i < bytes.length; i += 100) {
     				byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(bytes, i,i + 100));
     				sb.append(new String(doFinal));
     				dataReturn = ArrayUtils.addAll(dataReturn, doFinal);
     			}
        String outStr = Base64.getEncoder().encodeToString(dataReturn);
        return outStr;
    }
    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception {
    	//64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str);
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        
        byte[] dataReturn = {};
        // 解密时超过128字节就报错。为此采用分段解密的办法来解密
     	StringBuilder sb = new StringBuilder();
     	for (int i = 0; i < inputByte.length; i += 128) {
     		byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(inputByte, i,
     				i + 128));	
     		sb.append(new String(doFinal));
     	}
     	dataReturn = sb.toString().getBytes("UTF-8");
        
        String outStr = new String(dataReturn);
        return outStr;
    }

}

2.测试

		 long temp = System.currentTimeMillis();
	        //生成公钥和私钥
	        //加密字符串
		 List<String> genKeyPair = RSAUtils.genKeyPair();
		 	String publicKey  = genKeyPair.get(0);
		 	String privateKey = genKeyPair.get(1);
	        System.out.println("公钥:" + publicKey);
	        System.out.println("私钥:" + privateKey);
	        System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
	        String message = "我是中文";
	        System.out.println("原文:" + message);
	        temp = System.currentTimeMillis();
	        String messageEn = RSAUtils.encrypt(message, publicKey);
	        System.out.println("密文:" + messageEn);
	        System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
	        temp = System.currentTimeMillis();
	        String messageDe = RSAUtils.decrypt("hgveRO0cVu+E6VZ1Npm0i0dpsq3dyUW9i2IeUACXNs/oz7XtXH0PxI+rkPt4URrQaUX2eAaBMxyzgdglPoNEA99+H1vTJt2aeQGphCpmof0f92zi4QAcdfwZFgv1kMg6fW5O8bxDUJJ6jMy+/uo4o/rWUVgRgiZFMK1U/cDcXbU=", "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJhbVs+9R35t4PxKQrz1UY6eI8K4n1XTzX/L2jrAFFFcvSmF0GkA2oIE0EsbvUnebZdcIUnGS4CNEnJvRB2a6m2+ELIZQ8UwGTt/4rjbo6f1ZqJqMulBTCx7JTzYf0gkfaLAj3o9hvSgBXsgtcUQ/EP1rdQ3ElWsYxgiz3ieygM9AgMBAAECgYA71/S7WG+Sm3o53rlkGz/Tsw382CPNxIn9XobzeKsCYljyzFrWQ72QQG/IcLbjIvkM8OUqYzcY4VCTnly0/DqEEVj3rGb+6zWvnSs1i10okZN+YvlwmCu/8lsO2mWaPPMNK5DfXiDlqT4bAR8z+jsATSrhMYLXJrfBzvlRU7ibiQJBAMzzgrmGNvDL6diwy8POgbuT3lSDpF68gc4JoLi7nwOvJrr5WDrpmC+w2+/GOZ4mwB6BmQlYVBaLbgyMOjPUpmcCQQC+TjP0cuqc5ZYLke0v1Rw2zKkCnLdftB+RF9vL3Xicm2L+lbnMWl/wH8CsVEZlsnbPpIpLvWF/avE0hgfFQhq7AkEAvsdJ/4KU788Q7bmc47b+AmrhwZAM2Hbm6bECoBNeMOLAzbk/TQ+Wr4YVJPxDNBlkKsF+gDlthNLjbOC3aPngrwJBAIyFIkf2Mtb3j/urHQCc0+CC7qlHHwBD+KsieuHl/xFki4yA8li6wuyEBbk54WFmjeR1EskqZbu4M7Mc5M/7J9ECQDMIVtRNyHGZVD8G/BdtwEZ+VwvI6nCPa9BeYLnVzSLx5zm1kNeAvWONmdFy5E018j8gMIPNvvoFCrZue+7487k=");
	        //System.out.println("解密:" + messageDe);
	        //System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
//		
		String httpPost = HttpClientUtil.httpPost("http://127.0.0.1:9001/api/test", messageEn, privateKey);
		

3.http工具类

package com.dstz.base.rest.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * HttpClientUtil 工具类
 *
 * @author Frez
 */
public class HttpClientUtil {

    // 设置默认超时时间为60s
    public static final int DEFAULT_TIME_OUT = 60 * 1000;
    // 默认字符集UTF-8
    public static final String DEFAULT_CHARSET = "UTF-8";

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);


    /**
     * http请求
     *
     * @param url
     * @param paramMap
     * @param charset
     * @param isPost
     * @return
     */
    public static String sendHttpRequest(String url, Map<String, String> paramMap, String charset, boolean isPost) {
        return sendHttpRequest(url, paramMap, charset, isPost, DEFAULT_TIME_OUT);
    }

    /**
     * http请求
     *
     * @param url
     * @param paramMap
     * @param charset
     * @param isPost
     * @param timeout
     * @return
     */
    public static String sendHttpRequest(String url, Map<String, String> paramMap, String charset, boolean isPost, int timeout) {
        if (isPost) {
            return httpPost(url, paramMap, charset, timeout);
        }
        return httpGet(url, paramMap, charset, timeout);
    }

    public static String httpPost(String url, Map<String, String> params) {
        return httpPost(url, params, DEFAULT_CHARSET, DEFAULT_TIME_OUT);
    }

    /**
     * post请求
     *
     * @param url
     * @param params
     * @param charset
     * @param timeout
     * @return
     */
    public static String httpPost(String url, Map<String, String> params, String charset, int timeout) {
        log.error("http request url: " + url + " charset:" + charset + " timeout: " + timeout + " request str: " + params);
        // 参数组装
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            pairs.add(new BasicNameValuePair(key, formatStr(value)));
        }
        HttpEntity httpEntity;
        try {
            httpEntity = new UrlEncodedFormEntity(pairs);
            return httpPost(url, charset, timeout, httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String httpPost(String url, String jsonStr) {
        return httpPost(url, jsonStr, "UTF-8", DEFAULT_TIME_OUT);
    }
    
    
    /**
     * post请求
     *
     * @param url
     * @param jsonStr
     * @param token 
     * @return
     */
    public static String httpPost(String url, String jsonStr,String token) {
        return httpPost(url, jsonStr, "UTF-8", DEFAULT_TIME_OUT,token);
    }


    /**
     * post请求
     *
     * @param url
     * @param jsonStr
     * @param charset
     * @param timeout
     * @return
     */
    public static String httpPost(String url, String jsonStr, String charset, int timeout,String token) {
        log.error("http request url: " + url + " charset:" + charset + " timeout: " + timeout + " request jsonStr: " + jsonStr+ " token : " + token);
        HttpEntity httpEntity = null;
        httpEntity = new StringEntity(jsonStr, charset);
		return httpPost(url, charset, timeout, httpEntity,token);
    }

	/**
     * post请求
     *
     * @param url
     * @param jsonStr
     * @param charset
     * @param timeout
     * @return
     */
    public static String httpPost(String url, String jsonStr, String charset, int timeout) {
        log.error("http request url: " + url + " charset:" + charset + " timeout: " + timeout + " request jsonStr: " + jsonStr);
        HttpEntity httpEntity = null;
        httpEntity = new StringEntity(jsonStr, charset);
		return httpPost(url, charset, timeout, httpEntity);
    }

    public static String httpPost(String url, HttpEntity httpEntity) {
        return httpPost(url, "UTF-8", DEFAULT_TIME_OUT, httpEntity);
    }
    
    /**
     * post请求
     *
     * @param url
     * @param charset
     * @param timeout
     * @param httpEntity
     * @return
     */
    public static String httpPost(String url, String charset, int timeout, HttpEntity httpEntity,String token) {
        log.error("http url:" + url);
        if (url == null || url.equals("")) {
            return null;
        }
        String result = null;
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String responseBody = null;
        HttpResponse httpResponse = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
            httpClient = new DefaultHttpClient(httpParams);
            httpPost = new HttpPost(url);
            httpPost.setEntity(httpEntity);
			httpPost.setHeader("token", token);
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = httpResponse.getEntity();
            responseBody = EntityUtils.toString(entity, charset);
            result = responseBody;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (httpClient != null) {
                    httpClient.getConnectionManager().shutdown();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.error("http return:" + result);
        return result;
    }

    /**
     * post请求
     *
     * @param url
     * @param charset
     * @param timeout
     * @param httpEntity
     * @return
     */
    public static String httpPost(String url, String charset, int timeout, HttpEntity httpEntity) {
        log.error("http url:" + url);
        if (url == null || url.equals("")) {
            return null;
        }
        String result = null;
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String responseBody = null;
        HttpResponse httpResponse = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
            httpClient = new DefaultHttpClient(httpParams);
            httpPost = new HttpPost(url);
            httpPost.setEntity(httpEntity);
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = httpResponse.getEntity();
            responseBody = EntityUtils.toString(entity, charset);
            result = responseBody;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (httpClient != null) {
                    httpClient.getConnectionManager().shutdown();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.error("http return:" + result);
        return result;
    }

    /**
     * get请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String httpGet(String url, Map<String, String> params) {
        return httpGet(url, params, "UTF-8", DEFAULT_TIME_OUT);
    }

    /**
     * get请求
     *
     * @param url
     * @param params
     * @param charset
     * @param timeout
     * @return
     */
    public static String httpGet(String url, Map<String, String> params, String charset, int timeout) {
        HttpClient httpClient = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIME_OUT);
            httpClient = new DefaultHttpClient(httpParams);
            HttpEntity httpEntity = httpGetEntity(httpClient, url, params, DEFAULT_CHARSET);
            return EntityUtils.toString(httpEntity, charset);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.getConnectionManager().shutdown();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @param params
     * @param charset
     * @param timeout
     * @return
     */
    public static byte[] httpGetBytes(String url, Map<String, String> params) {
        HttpClient httpClient = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIME_OUT);
            httpClient = new DefaultHttpClient(httpParams);
            HttpEntity httpEntity = httpGetEntity(httpClient, url, params, DEFAULT_CHARSET);
            return EntityUtils.toByteArray(httpEntity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.getConnectionManager().shutdown();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @param params
     * @param charset
     * @param timeout
     * @return
     */
    public static HttpEntity httpGetEntity(HttpClient httpClient, String url, Map<String, String> params, String charset) {
        log.error("http request url: " + url + " charset:" + charset + " request str: " + params);
        if (url == null || url.equals("")) {
            return null;
        }
        HttpGet httpGet;
        HttpResponse httpResponse;
        HttpEntity entity = null;
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                for (Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    pairs.add(new BasicNameValuePair(key, formatStr(value)));
                }
                url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            entity = httpResponse.getEntity();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }

    private static String formatStr(String text) {
        return (null == text ? "" : text.trim());
    }
}
发布了240 篇原创文章 · 获赞 66 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u014131617/article/details/100585163
今日推荐