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;
public class RSAUtils {
private final static int KEY_SIZE = 1024;
public static List<String> genKeyPair() throws NoSuchAlgorithmException {
List<String> keyList = new ArrayList();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
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());
keyList.add(publicKeyString);
keyList.add(privateKeyString);
return keyList;
}
public static String encrypt(String str, String publicKey) throws Exception {
byte[] decoded = Base64.getDecoder().decode(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] bytes = str.getBytes("UTF-8");
byte[] dataReturn = {};
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;
}
public static String decrypt(String str, String privateKey) throws Exception {
byte[] inputByte = Base64.getDecoder().decode(str);
byte[] decoded = Base64.getDecoder().decode(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, priKey);
byte[] dataReturn = {};
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=");
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;
public class HttpClientUtil {
public static final int DEFAULT_TIME_OUT = 60 * 1000;
public static final String DEFAULT_CHARSET = "UTF-8";
private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
public static String sendHttpRequest(String url, Map<String, String> paramMap, String charset, boolean isPost) {
return sendHttpRequest(url, paramMap, charset, isPost, DEFAULT_TIME_OUT);
}
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);
}
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;
}
public static String httpPost(String url, String jsonStr) {
return httpPost(url, jsonStr, "UTF-8", DEFAULT_TIME_OUT);
}
public static String httpPost(String url, String jsonStr,String token) {
return httpPost(url, jsonStr, "UTF-8", DEFAULT_TIME_OUT,token);
}
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);
}
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);
}
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;
}
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;
}
public static String httpGet(String url, Map<String, String> params) {
return httpGet(url, params, "UTF-8", DEFAULT_TIME_OUT);
}
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;
}
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;
}
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());
}
}