以下是使用过或者看到觉得还不错的工具类,总结出来了
1.在对象装JSON类型的时候使用的Jackson 工具类
代码:
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* The class JacksonUtil
*
* json字符与对像转换
*
* @version: $Revision$ $Date$ $LastChangedBy$
*
*/
public final class JacksonUtil {
public static ObjectMapper objectMapper;
/**
* 使用泛型方法,把json字符串转换为相应的JavaBean对象。
* (1)转换为普通JavaBean:readValue(json,Student.class)
* (2)转换为List,如List<Student>,将第二个参数传递为Student
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
*
* @param jsonStr
* @param valueType
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true) ;
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json数组转List
* @param jsonStr
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 把JavaBean转换为json字符串
*
* @param object
* @return
*/
public static String toJSon(Object object) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings({ "unchecked" })
public static Map<String, Object> Json2Map(String json) {
Map<String, Object> result = null;
// write your code here
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
try {
result = mapper.readValue(json, Map.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
。
。
。
2.http get请求中文传参问题,使用encodeResult 和 decodeResult 解决,UrlUtil 工具类
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class UrlUtil {
private static final String CHARSET = "UTF-8";
public static String encode(String content) {
String encodeResult = null;
try {
encodeResult = URLEncoder.encode(content, CHARSET);
} catch (UnsupportedEncodingException e) {
log.error("encode error", e);
}
return encodeResult;
}
public static String decode(String content) {
String decodeResult = null;
try {
decodeResult = URLDecoder.decode(content, CHARSET);
} catch (UnsupportedEncodingException e) {
log.error("decode error", e);
}
return decodeResult;
}
}
。
。
。
3.二维码工具类,暂时还没用过
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.springframework.util.ResourceUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
public class QrCodeUtil {
// 二维码颜色==黑色
private static final int BLACK = 0xFF000000;
// 二维码颜色==白色
private static final int WHITE = 0xFFFFFFFF;
public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
return pngData;
}
/**
* 二维码流的形式,包含文本内容
*
* @param content 二维码文本内容
* @param size 二维码尺寸
* @param logoPath logo的存放位置
* @return
* @throws IOException
*/
public static byte[] getBufferedImage(String content, Integer size, String logoPath) throws IOException {
if (size == null || size <= 0) {
size = 250;
}
BufferedImage image = null;
try {
// 设置编码字符集
Map<EncodeHintType, Object> hints = new HashMap<>();
//设置编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//设置容错率最高
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 1);
// 1、生成二维码
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
// 2、获取二维码宽高
int codeWidth = bitMatrix.getWidth();
int codeHeight = bitMatrix.getHeight();
// 3、将二维码放入缓冲流
image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < codeWidth; i++) {
for (int j = 0; j < codeHeight; j++) {
// 4、循环将二维码内容定入图片
image.setRGB(i, j, bitMatrix.get(i, j) ? BLACK : WHITE);
}
}
//判断是否写入logo图片
if (logoPath != null && !"".equals(logoPath)) {
File logoPic = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/images/company.png");
if (logoPic.exists()) {
Graphics2D g = image.createGraphics();
BufferedImage logo = ImageIO.read(logoPic);
int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
int x = (image.getWidth() - widthLogo) / 2;
int y = (image.getHeight() - heightLogo) / 2;
// 开始绘制图片
g.drawImage(logo, x, y, widthLogo, heightLogo, null);
g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
//边框宽度
g.setStroke(new BasicStroke(2));
//边框颜色
g.setColor(Color.WHITE);
g.drawRect(x, y, widthLogo, heightLogo);
g.dispose();
logo.flush();
image.flush();
}
}
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
return out.toByteArray();
}
}
.
.
.
4.通过长度获取26字母与0-9的随机数,NumberUtil 工具类
import java.util.Random;
public class NumberUtil {
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rd = new Random();
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < length; i++) {
int number = rd.nextInt(str.length());
sb.append(str.charAt(number));
}
return sb.toString();
}
}
。
。
。
5.StringUtils 工具类
maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
StringUtils里面的方法比较多,可以使用
if (StringUtils.isEmpty(str)) {
}
来进行判断,还以避免一些空指针的发生
还可通过这个工具类获取固定长度字符串,不足的部分补齐
StringUtils.leftPad("test", 8, "0");
字符串关键字替换
StringUtils 提供一些列的方法,可以替换某些关键字:
// 默认替换所有关键字
StringUtils.replace("aba", "a", "z") = "zbz";
// 替换关键字,仅替换一次
StringUtils.replaceOnce("aba", "a", "z") = "zba";
// 使用正则表达式替换
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123";
字符串拼接
字符串拼接是个常见的需求,简单办法使用 StringBuilder 循环遍历拼接:
String[] array = new String[]{"test", "1234", "5678"};
StringBuilder stringBuilder = new StringBuilder();
for (String s : array) {
stringBuilder.append(s).append(";");
}
// 防止最终拼接字符串为空
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
System.out.println(stringBuilder.toString());
这里我们可以直接使用以下方法获取拼接之后字符串:
StringUtils.join(["a", "b", "c"], ",") = "a,b,c"
StringUtils 只能传入数组拼接字符串,不过我比较喜欢集合拼接,所以再推荐下 Guava 的 Joiner。
实例代码如下:
String[] array = new String[]{"test", "1234", "5678"};
List<String> list=new ArrayList<>();
list.add("test");
list.add("1234");
list.add("5678");
StringUtils.join(array, ",");
// 逗号分隔符,跳过 null
Joiner joiner=Joiner.on(",").skipNulls();
joiner.join(array);
joiner.join(list);
字符串拆分
有字符串拼接,就会有拆分字符串的需求,同样的 StringUtils 也有拆分字符串的方法。
StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
StringUtils.splitByWholeSeparatorPreserveAllTokens("a..b.c", ".")= ["a","", "b", "c"]
StringUtils 拆分之后得到是一个数组,可以使用 Guava 的
Splitter splitter = Splitter.on(",");
// 返回是一个 List 集合,结果:[ab, , b, c]
splitter.splitToList("ab,,b,c");
// 忽略空字符串,输出结果 [ab, b, c]
splitter.omitEmptyStrings().splitToList("ab,,b,c")
。
。
。
6.日期相关工具类 — DateUtils/DateFormatUtils
之前写的 SimpleDateFormat,不是线程安全的
// Date 转化为字符串
DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
// 字符串 转 Date
DateUtils.parseDate("2020-05-07 22:00:00","yyyy-MM-dd HH:mm:ss");
除了格式转化之外,DateUtils 还提供时间计算的相关功能。
Date now = new Date();
// Date 加 1 天
Date addDays = DateUtils.addDays(now, 1);
// Date 加 33 分钟
Date addMinutes = DateUtils.addMinutes(now, 33);
// Date 减去 233 秒
Date addSeconds = DateUtils.addSeconds(now, -233);
// 判断是否 Wie 同一天
boolean sameDay = DateUtils.isSameDay(addDays, addMinutes);
// 过滤时分秒,若 now 为 2020-05-07 22:13:00 调用 truncate 方法以后
// 返回时间为 2020-05-07 00:00:00
Date truncate = DateUtils.truncate(now, Calendar.DATE);
.
.
.
7.JDK8 时间类
DK8 之后,Java 将日期与时间分为 LocalDate,LocalTime,功能定义更加清晰,当然其也提供一个 LocalDateTime,包含日期与时间。这些类相对于 Date 类优点在于,这些类与 String 类一样都是不变类型,不但线程安全,而且不能修改。
ps:仔细对比 mysql 时间日期类型 DATE,TIME,DATETIME,有没有感觉差不多
现在 mybatis 等 ORM 框架已经支持 LocalDate 与 JDBC 时间类型转化,所以大家可以直接将时间字段实际类型定义为 JDK8 时间类型,然后再进行相关转化。
如果依然使用的是 Date 类型,如果需要使用新的时间类型,我们需要进行相关转化。两者之间进行转化, 稍微复杂一点,我们需要显示指定当前时区。
Date now = new Date();
// Date-----> LocalDateTime 这里指定使用当前系统默认时区
LocalDateTime localDateTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
// LocalDateTime------> Date 这里指定使用当前系统默认时区
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
接下来我们使用 LocalDateTime 进行字符串格式化。
// 按照 yyyy-MM-dd HH:mm:ss 转化时间
LocalDateTime dateTime = LocalDateTime.parse("2020-05-07 22:34:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 将 LocalDateTime 格式化字符串
String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
另外我们使用 LocalDateTime 获取当前时间年份,月份特别简单:
LocalDateTime now = LocalDateTime.now();
// 年
int year = now.getYear();
// 月
int month = now.getMonthValue();
// 日
int day = now.getDayOfMonth();
最后我们还可以使用 LocalDateTime 进行日期加减,获取下一天的时间:
LocalDateTime now = LocalDateTime.now();
// 当前时间加一天
LocalDateTime plusDays = now.plusDays(1l);
// 当前时间减一个小时
LocalDateTime minusHours = now.minusHours(1l);
// 还有很多其他方法
.
.
.
8.集合/数组相关
之前经常使用的
if (null == list || list.isEmpty()) {
}
非空判断容易出现空指针异常
这里可以使用 commons-collections 提供工具类。
maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</vesion>
</dependency>
使用 CollectionUtils/MapUtils进行判空判断。
// List/Set 集合判空
if(CollectionUtils.isEmpty(list)){
}
// Map 等集合进行判空
if (MapUtils.isEmpty(map)) {
}
至于数组判空判断需要使用 commons-lang 下的 ArrayUtils进行判断:
// 数组判空
if (ArrayUtils.isEmpty(array)) {
}
除此之外还有一些列的对于集合增强方法,比如快速将数组加入到现有集合中:
List<String> listA = new ArrayList<>();
listA.add("1");
listA.add("2");
listA.add("3");
String[] arrays = new String[]{"a", "b", "c"};
CollectionUtils.addAll(listA, arrays);
。
。
。
9.I/O 相关
Apache 提供的 commons-io 库,增强 I/O 操作,简化操作难度。pom 信息:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
FileUtils-文件操作工具类
快速实现文件/文件夹拷贝操作 ,FileUtils.copyDirectory/FileUtils.copyFile
// 拷贝文件
File fileA = new File("E:\\test\\test.txt");
File fileB = new File("E:\\test1\\test.txt");
FileUtils.copyFile(fileA,fileB);
使用 FileUtils.listFiles 获取指定文件夹上所有文件
// 按照指定文件后缀如java,txt等去查找指定文件夹的文件
File directory = new File("E:\\test");
FileUtils.listFiles(directory, new String[]{"txt"}, false);
使用 FileUtils.readLines 读取该文件所有行。
// 读取指定文件所有行 不需要使用 while 循环读取流了
List<String> lines = FileUtils.readLines(fileA)
有读就存在写,可以使用 FileUtils.writeLines,直接将集合中数据,一行行写入文本。
// 可以一行行写入文本
List<String> lines = new ArrayList<>();
.....
FileUtils.writeLines(lines)
IOUtils-I/O 操作相关工具类
FileUtils 主要针对相关文件操作,IOUtils 更加针对底层 I/O,可以快速读取 InputStream。实际上 FileUtils 底层操作依赖就是 IOUtils。
IOUtils可以适用于一个比较试用的场景,比如支付场景下,HTTP 异步通知场景。如果我们使用 JDK 原生方法写:
从 Servlet 获取异步通知内容
byte[] b = null;
ByteArrayOutputStream baos = null;
String respMsg = null;
try {
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
// 获取输入流
InputStream in = request.getInputStream();
for (int len = 0; (len = in.read(buffer)) > 0; ) {
baos.write(buffer, 0, len);
}
b = baos.toByteArray();
baos.close();
// 字节数组转化成字符串
String reqMessage = new String(b, "utf-8");
} catch (IOException e) {
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
}
}
}
上面代码说起来还是挺复杂的。不过我们使用 IOUtils,一个方法就可以简单搞定:
// 将输入流信息全部输出到字节数组中
byte[] b = IOUtils.toByteArray(request.getInputStream());
// 将输入流信息转化为字符串
String resMsg = IOUtils.toString(request.getInputStream());
.
.
.
10.计时
Guava Stopwatch 计时工具类
// 创建之后立刻计时,若想主动开始计时
Stopwatch stopwatch = Stopwatch.createStarted();
// 创建计时器,但是需要主动调用 start 方法开始计时
// Stopwatch stopwatch = Stopwatch.createUnstarted();
// stopWatch.start();
// 模拟其他代码耗时
TimeUnit.SECONDS.sleep(2l);
// 当前已经消耗的时间
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));;
TimeUnit.SECONDS.sleep(2l);
// 停止计时 未开始的计时器调用 stop 将会抛错 IllegalStateException
stopwatch.stop();
// 再次统计总耗时
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));;
// 重新开始,将会在原来时间基础计算,若想重新从 0开始计算,需要调用 stopwatch.reset()
stopwatch.start();
TimeUnit.SECONDS.sleep(2l);
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));
。
。
。
11.读取配置文件
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class TestProperties {
/**
* 根据key读取value
*
* @Title: getProperties_2 @Description: 第二种方式:使用缓冲输入流读取配置文件,然后将其加载,再按需操作
* 绝对路径或相对路径, 如果是相对路径,则从当前项目下的目录开始计算,
* 如:当前项目路径/config/config.properties, 相对路径就是config/config.properties
*
* @param filePath
* @param keyWord @return @return String @throws
*/
public static String getProperties(String filePath, String keyWord) {
Properties p = new Properties();
InputStream in = TestProperties.class.getResourceAsStream(filePath);
try {
p.load(in);
return p.get(keyWord).toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
然后通过方法传入路径获取参数
public class ConfigUtil {
public static String servicesUrl(){
String properties = TestProperties.getProperties("/config/config.properties", "servicesUrl");
return properties;
}
}
.
.
.
12.发送 http 请求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
@SuppressWarnings("all")
public class HttpRequest {
private static final int TIMEOUT = 30 * 1000;
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) throws Exception{
String result = "";
BufferedReader in = null;
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("charsert", "UTF-8");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) throws Exception{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
// try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// System.out.println("URLConnection Go");
//entity为请求体部分内容
//如果有中文则以UTF-8编码为username=%E4%B8%AD%E5%9B%BD&password=123
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("charsert", "UTF-8");
// System.out.println("URLConnection GoGO");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// System.out.println("URLConnection GoGOGO");
// 获取URLConnection对象对应的输出流
// out = new PrintWriter(conn.getOutputStream());
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// System.out.println("URLConnection GoGOGOGO");
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
public static String sendHttpPost(String url,String paramName,String param,String charSet){
String response="";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(paramName,param));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params,charSet);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(entity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200){
System.out.println("请求和响应成功");
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
System.out.println(response);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
public static String sendHttpPost(String url,String params,String charSet){
String response="";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url+"?"+params);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200){
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param,String charset) throws Exception{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
//entity为请求体部分内容
//如果有中文则以UTF-8编码为username=%E4%B8%AD%E5%9B%BD&password=123
// 设置通用的请求属性
conn.setRequestProperty("accept", "text/plan");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("charsert", "UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
// out = new PrintWriter(conn.getOutputStream());
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),charset));
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
public static String httpPostWithJson(net.sf.json.JSONObject jsonObj,String url) throws Exception{
String resultStr = "";
HttpPost post = null;
HttpClient httpClient = new DefaultHttpClient();
// 设置超时时间
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
post = new HttpPost(url);
// 构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
// 构建消息实体
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity httpEntity = response.getEntity();
resultStr = EntityUtils.toString(httpEntity,"UTF-8");
return resultStr;
}
public static String httpPutWithJson(net.sf.json.JSONObject jsonObj,String url) throws Exception{
String resultStr = "";
HttpPut put = null;
HttpClient httpClient = new DefaultHttpClient();
// 设置超时时间
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
put = new HttpPut(url);
// 构造消息头
put.setHeader("Content-type", "application/json; charset=utf-8");
// 构建消息实体
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
put.setEntity(entity);
HttpResponse response = httpClient.execute(put);
HttpEntity httpEntity = response.getEntity();
resultStr = EntityUtils.toString(httpEntity,"UTF-8");
return resultStr;
}
public static String sendHttpPost(net.sf.json.JSONObject jsonObj,String serverURL,String token) throws Exception{
StringBuffer sbf = new StringBuffer();
String strRead = null;
URL url = new URL(serverURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");//请求post方式
connection.setDoInput(true);
connection.setDoOutput(true);
//header内的的参数在这里set connection.setRequestProperty("健, "值");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("x-token", token);
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
//body参数在这里put到JSONObject中
writer.write(jsonObj.toString());
writer.flush();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
connection.disconnect();
String results = sbf.toString();
return results;
}
/**
* http get请求
* @param httpUrl 链接
* @return 响应数据
*/
public static String doGet(String httpUrl){
//链接
HttpURLConnection connection=null;
InputStream is=null;
BufferedReader br = null;
StringBuffer result=new StringBuffer();
try {
//创建连接
URL url=new URL(httpUrl);
connection= (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置连接超时时间
connection.setConnectTimeout(15000);
//设置读取超时时间
connection.setReadTimeout(15000);
//开始连接
connection.connect();
//获取响应数据
if(connection.getResponseCode()==200){
//获取返回的数据
is=connection.getInputStream();
if(is!=null){
br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
String temp = null;
while ((temp=br.readLine())!=null){
result.append(temp);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();// 关闭远程连接
}
return result.toString();
}
/**
* post请求
* @param httpUrl 链接
* @param param 参数
* @return
*/
public static String doPost(String httpUrl,String param) {
StringBuffer result=new StringBuffer();
//连接
HttpURLConnection connection=null;
OutputStream os=null;
InputStream is=null;
BufferedReader br=null;
try {
//创建连接对象
URL url=new URL(httpUrl+"?"+param);
//创建连接
connection= (HttpURLConnection) url.openConnection();
//设置请求方法
connection.setRequestMethod("POST");
//设置连接超时时间
connection.setConnectTimeout(15000);
//设置读取超时时间
connection.setReadTimeout(15000);
//设置是否可读取
connection.setDoOutput(true);
//设置响应是否可读取
connection.setDoInput(true);
//设置参数类型
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type", "text/plain");
//拼装参数
if(param!=null&&!param.equals("")){
//设置参数
os=connection.getOutputStream();
//拼装参数
os.write(param.getBytes("UTF-8"));
}
//设置权限
//设置请求头等
//开启连接
//connection.connect();
//读取响应
if(connection.getResponseCode()==200){
is=connection.getInputStream();
if(is!=null){
br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
String temp=null;
if((temp=br.readLine())!=null){
result.append(temp);
}
}
}
//关闭连接
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
connection.disconnect();
}
return result.toString();
}
}
.
.
.
13.xml 工具类
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
@SuppressWarnings("all")
public class XmlConverUtil {
public Map<String, Object> rowMap;
public Map<String, Object> getRowMap() {
return rowMap;
}
public void setRowMap(Map<String, Object> rowMap) {
this.rowMap = rowMap;
}
private Map<String, Object> map = new HashMap<>();
public Map<String,Object> xmlElements(String xmlDoc) throws DocumentException {
//创建一个新的字符串
StringReader read = new StringReader(xmlDoc);
//创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
//创建一个新的SAXBuilder
SAXReader saxReader = new SAXReader();
Document document=saxReader.read(source);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root=document.getRootElement();//获取根节点
this.getNodes(root);//从根节点开始遍历所有节点
rowMap = map;
return rowMap;
}
/**
* 从指定节点开始,递归遍历所有子节点
* @author chenleixing
*/
public void getNodes(Element node){
//当前节点的名称、文本内容和属性
map.put(node.getName(), node.getTextTrim());
// System.out.println("当前节点名称:"+node.getName());//当前节点名称
// System.out.println("当前节点的内容:"+node.getTextTrim());//当前节点名称
List<Attribute> listAttr=node.attributes();//当前节点的所有属性的list
for(Attribute attr:listAttr){//遍历当前节点的所有属性
String name=attr.getName();//属性名称
String value=attr.getValue();//属性的值
map.put(name, value);
// System.out.println("属性名称:"+name+"属性值:"+value);
}
//递归遍历当前节点所有的子节点
List<Element> listElement=node.elements();//所有一级子节点的list
for(Element e:listElement){//遍历所有一级子节点
this.getNodes(e);//递归
}
}
public List<Map<String,Object>> xmlElementsByNodes(String xmlDoc) throws DocumentException
{
List<Map<String, Object>> listMap = new ArrayList<>();
//创建一个新的字符串
StringReader read = new StringReader(xmlDoc);
//创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
//创建一个新的SAXBuilder
SAXReader saxReader = new SAXReader();
Document document=saxReader.read(source);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root=document.getRootElement();//获取根节点
Element response = root.element("response");
Element departments = response.element("departments");
List<Element> list = departments.elements();
for(Element ele:list){
List<Element> listAttr=ele.elements();//当前节点的所有属性的list
map = new HashMap<>();
for(Element attr:listAttr){//遍历当前节点的所有属性
String name=attr.getName();//属性名称
String value=attr.getTextTrim();//属性的值
map.put(name, value);
}
listMap.add(map);
}
return listMap;
}
public List<Map<String,Object>> xmlElementsByinHsop(String xmlDoc) throws DocumentException
{
List<Map<String, Object>> listMap = new ArrayList<>();
//创建一个新的字符串
StringReader read = new StringReader(xmlDoc);
//创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
//创建一个新的SAXBuilder
SAXReader saxReader = new SAXReader();
Document document=saxReader.read(source);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root=document.getRootElement();//获取根节点
List<Element> list = root.elements();
for(Element ele:list){
List<Element> listAttr=ele.elements();//当前节点的所有属性的list
map = new HashMap<>();
for(Element attr:listAttr){//遍历当前节点的所有属性
String name=attr.getName();//属性名称
String value=attr.getTextTrim();//属性的值
map.put(name, value);
}
listMap.add(map);
}
return listMap;
}
}
.
.
.
14.加密排序工具类
AESutil 工具类
import java.io.UnsupportedEncodingException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
public class AESutil {
/**
* 算法/模式/填充
**/
private static final String CipherMode = "AES/ECB/PKCS7Padding";
/**
* 创建密钥
**/
private static SecretKeySpec createKey(String password) {
byte[] data = null;
if (password == null) {
password = "";
}
StringBuffer sb = new StringBuffer(32);
sb.append(password);
while (sb.length() < 32) {
sb.append("0");
}
if (sb.length() > 32) {
sb.setLength(32);
}
try {
data = sb.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// log.error("createKey error: ", e);
}
return new SecretKeySpec(data, "AES");
}
public static String create32Key(String password) {
StringBuffer sb = new StringBuffer(32);
sb.append(password);
while (sb.length() < 32) {
sb.append("0");
}
if (sb.length() > 32) {
sb.setLength(32);
}
return sb.toString();
}
/**
* 加密字节数据
**/
public static byte[] encryptJava(byte[] content, String password) {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
SecretKeySpec key = createKey(password);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
// log.error("encryptJava error: ", e);
}
return null;
}
/**
* 解密字节数组
**/
public static byte[] decryptJava(byte[] content, String password) {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
SecretKeySpec key = createKey(password);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
// log.error("decryptJava error: ", e);
}
return null;
}
/**
* 加密(结果为16进制字符串)
**/
public static String encryptJava(String content, String password) {
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(content)) {
return content;
}
byte[] data = null;
try {
data = content.getBytes("UTF-8");
} catch (Exception e) {
// log.error("encryptJava error: ", e);
}
data = encryptJava(data, password);
return Base64Utils.encode(data);
}
public static String decryptJava(String content, String password) {
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(content)) {
return content;
}
if (StringUtils.isEmpty(password)) {
return content;
}
byte[] data = decryptJava(Base64Utils.decode(content), password);
if (data == null) {
return null;
}
String result = "";
try {
result = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
// log.error("decrypt error: ", e);
}
return result;
}
/**
* 加密(结果为16进制字符串)
**/
public static String encrypt(String content, String password) {
return encryptJava(content, password);
}
/**
* 解密16进制的字符串为字符串
**/
public static String decrypt(String content, String password) {
return decryptJava(content, password);
}
public static void main(String[] args) {
}
}
.
.
.
MD5加密工具类
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import leantech.app.validator.SignValidator;
public class Md5 {
// public final static String md5key = "T8NisJuAG8vChySheeJgqg=="; //
private static final Logger LOGGER = Logger.getLogger(SignValidator.class);
/**
* MD5方法
*
* @param text
* 明文
* @param key
* 密钥
* @return 密文
* @throws Exception
*/
public static String md5(String text, String key) throws Exception {
// 加密后的字符串
String encodeStr = DigestUtils.md5Hex(text + key);
LOGGER.info("************************签名后的字符串为: "+ encodeStr);
return encodeStr;
}
/**
* MD5验证方法
*
* @param text
* 明文
* @param key
* 密钥
* @param md5
* 密文
* @return true/false
* @throws Exception
*/
public static boolean verify(String text, String key, String md5) throws Exception {
// 根据传入的密钥进行验证
String md5Text = md5(text, key);
if (md5Text.equalsIgnoreCase(md5)) {
return true;
}
return false;
}
public static String md5Str(String str) {
if (str == null)
return "";
return md5Str(str, 0);
}
/**
* 计算消息摘要。
*
* @param data
* 计算摘要的数据。
* @param offset
* 数据偏移地址。
* @param length
* 数据长度。
* @return 摘要结果。(16字节)
*/
public static String md5Str(String str, int offset) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] b = str.getBytes("UTF8");
md5.update(b, offset, b.length);
return byteArrayToHexString(md5.digest());
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return null;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
return null;
}
}
/**
*
* @param b
* byte[]
* @return String
*/
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += byteToHexString(b[i]);
}
return result;
}
private static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e",
"f" };
/**
* 将字节转换为对应的16进制明文
*
* @param b
* byte
* @return String
*/
public static String byteToHexString(byte b) {
int n = b;
if (n < 0) {
n = 256 + n;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
}
.
.
.
RSA加密工具类
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import leantech.app.exception.RsaException;
import net.sf.json.JSONObject;
/**
* 非对称加密算法RSA算法组件 非对称算法一般是用来传送对称加密算法的密钥来使用的,相对于DH算法,RSA算法只需要一方构造密钥,不需要
* 大费周章的构造各自本地的密钥对了。DH算法只能算法非对称算法的底层实现。而RSA算法算法实现起来较为简单
*
* @author kongqz
*/
public class RSACoder {
/**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
/**
* 获取密钥对
*
* @return 密钥对
*/
public static KeyPair getKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
generator.initialize(1024);
return generator.generateKeyPair();
}
/**
* 获取私钥
*
* @param privateKey 私钥字符串
* @return
*/
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
return keyFactory.generatePrivate(keySpec);
}
/**
* 获取公钥
*
* @param publicKey 公钥字符串
* @return
*/
public static PublicKey getPublicKey(String publicKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
return keyFactory.generatePublic(keySpec);
}
/**
* RSA公钥加密
*
* @param data 待加密数据
* @param publicKey 公钥
* @return
*/
public static String encryptByPublicKey(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
// 加密后的字符串
return new String(Base64.encodeBase64String(encryptedData));
}
/**
* RSA公钥解密
*
* @param data 待解密数据
* @param publicKey 公钥
* @return
*/
public static String decryptByPublicKey(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] dataBytes = Base64.decodeBase64(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
return new String(decryptedData, "UTF-8");
}
/**
* RSA私钥加密
*
* @param data 待加密数据
* @param publicKey 公钥
* @return
*/
public static String encryptByPrivateKey(String data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
// 加密后的字符串
return new String(Base64.encodeBase64String(encryptedData));
}
/**
* RSA私钥解密
*
* @param data 待解密数据
* @param privateKey 私钥
* @return
*/
public static String decryptByPrivateKey(String data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.decodeBase64(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
return new String(decryptedData, "UTF-8");
}
/**
* 签名
*
* @param data 待签名数据
* @param privateKey 私钥
* @return 签名
*/
public static String sign(String data, PrivateKey privateKey) throws Exception {
byte[] keyBytes = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(key);
signature.update(data.getBytes());
return new String(Base64.encodeBase64(signature.sign()));
}
/**
* 验签
*
* @param srcData 原始字符串
* @param publicKey 公钥
* @param sign 签名
* @return 是否验签通过
*/
public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
byte[] keyBytes = publicKey.getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(key);
signature.update(srcData.getBytes());
return signature.verify(Base64.decodeBase64(sign.getBytes()));
}
public static void main(String[] args) throws Exception {
String terminalPrivateKey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKs7NYBIIh38oS+sRsQOmfZuTtAJ8HPGFHF0R15/b5cJxN0+rIZ3sg6e3LAPZuFIOdzrf8GyznCsb3qbPTWtJ8kJCoxAxoEX+Tnnw4GH1Tu5eUoE5/+WFlHrA3O4tglQKAbL9Jey63E6oZs1+LAvEKQ8wO0pAqMCQmW7TUs50HkNAgMBAAECgYEAgr/cc48hFhrBDgETrEOmBwll/u+H/y+CjruGf775e7CG9ZYU8TzW5tkhlQK9wUqAfJQK4uJhRqI1Ib8Gd0U4OcWRHfJhJW2hmX6ju2xImRCJzJJ8GQk+lsAqwMJ9+CJ5QoTOngkT5oVpz16iErcc9eihwANuxGgjGw6N9NbyQfUCQQDpvCUvES+07pDheghgWpFK2Dzp41XpMsQPjWKgjnaL+3NlczI4E7WZWRmnZuUIHYyKtMjtYByqtV1xdHmmlz3TAkEAu4rZ3abFJ3CMCdDLwXgHiQ6XSrPRe7L94+JO4mqlVrqcR99e7FfF+i4xSnaXlgAtm5I7xNYdziC+jc7BFofBnwJASFlisSUCvWCzG/goK5sdKiuw/zzNVPfP1HiRNN2kOERHPfnga5c+OQ9pb3XcIxzyaeT35PJBLV4iZIIHPdfG3QJABZ+DKscuUCFqwXyWL2XW7AAY/y9nD4ttW2DUtqs16+TKfMkwwmtbT0YFSlNF9kRpGaoHyr4UxLJspDnXxkIpxwJAIMvT5A5zpTElMTIg4INerS2guoriKuSWU6JoyW680H7qSTLNo/w/fJUboNQ0bMnE9j0/2ISXq25GxJNISmTj6w==";
String terminalPublicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrOzWASCId/KEvrEbEDpn2bk7QCfBzxhRxdEdef2+XCcTdPqyGd7IOntywD2bhSDnc63/Bss5wrG96mz01rSfJCQqMQMaBF/k558OBh9U7uXlKBOf/lhZR6wNzuLYJUCgGy/SXsutxOqGbNfiwLxCkPMDtKQKjAkJlu01LOdB5DQIDAQAB";
// JSONObject json = new JSONObject();
// json.put("create_ip", "");
// json.put("notice_port", "");
// json.put("merchant_id", "610261010002");
// json.put("out_trade_no", "202101121128187496273");
// json.put("out_refund_no", "");
Map<String,String> map = new HashMap<String, String>();
map.put("appId", "appId");
map.put("bankType", "bankType");
map.put("cashFee", "cashFee");
map.put("cashFeeType", "cashFeeType");
map.put("errCode", "errCode");
map.put("errCodeDes", "errCodeDes");
map.put("feeType", "feeType");
map.put("merchantId", "merchantId");
map.put("nonceStr", "nonceStr");
String parm = encodeSign(map);
String sign = sign(parm, getPrivateKey(terminalPrivateKey));
boolean l = verify(parm, getPublicKey(terminalPublicKey),sign);
}
/**
* 签名校验
*
* @param terminalPublicKey
* @throws Exception
*/
public static void checkSign(String terminalPrivateKey,String terminalPublicKey, String param,String sign) {
String encodedData;
try {
encodedData = encryptByPrivateKey(param, getPrivateKey(terminalPrivateKey));
// if(!verify(encodedData, getPublicKey(terminalPublicKey),sign))
// {
// throw new RsaException("验签失败");
// }
} catch (Exception e) {
e.printStackTrace();
throw new RsaException("验签失败");
}
}
/**
* sign 签名 (参数名按ASCII码从小到大排序(字典序)+key+MD5+转大写签名)
* @param map
* @return
*/
public static String encodeSign(Map<String,String> map){
// 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
// 构造签名键值对的格式
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> item : infoIds) {
if (item.getKey() != null || item.getKey() != "") {
String key = item.getKey();
String val = item.getValue();
if (!(val == "" || val == null)) {
sb.append(key + "=" + val + "&");
}
}
}
return sb.toString();
}
}
先记到这边,部分文章引用自 这里