1、文件
1、根据图片的链接,下载图片
package com.lingxu.module.BigDataJoinMessage.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUtil {
public static boolean saveImageToDisk(String imgUrl, String fileName, String filePath) {
InputStream inputStream = null;
inputStream = getInputStream(imgUrl);
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath + fileName);
while ((len = inputStream.read(data))!=-1) {
fileOutputStream.write(data,0,len);
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally{
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static InputStream getInputStream(String imgUrl){
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(imgUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
inputStream = httpURLConnection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}
2、从后台的resource下,下载文件
@ApiOperation(value = "导出模板")
@GetMapping(value = "/exportPersonExcel")
public void downloadExcel(HttpServletResponse response) throws Exception {
try {
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("excelTemplates/干部信息导入模板.xls");
String fileName = "干部信息导入模板.xls";
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("fileName", fileName);
response.setHeader("Access-Control-Expose-Headers", "filename");
OutputStream out = response.getOutputStream();
byte[] b = new byte[2048];
int len;
while ((len = resourceAsStream.read(b)) != -1) {
out.write(b, 0, len);
}
out.close();
resourceAsStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
3、读取文件流进行全局替换,适合小文件
public static void main(String[] args){
String filePath = "D:\\sql\\UT_PERSON_INFO.sql";
String outPath = "D:\\sql\\UT_PERSON_INFO.sql";
try {
autoReplace(filePath,outPath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void autoReplace(String filePath, String outPath) throws IOException {
File file = new File(filePath);
Long fileLength = file.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = new FileInputStream(filePath);
in.read(fileContext);
in.close();
String str = new String(fileContext);
str = str.replace("\"PUBLIC\".", " ");
str = str.replace("\"", "'");
PrintWriter out = new PrintWriter(outPath);
out.write(str.toCharArray());
out.flush();
out.close();
}
4、读取文件,每行读取,然后替换指定的内容 删除指定的行数
public static void ChangeFile (String filePath, String outPath) throws IOException {
try {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));
StringBuffer strBuffer = new StringBuffer();
String empty = "";
String tihuan = "";
List<String> arrList = new ArrayList<>();
for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {
if(temp.contains("\"PUBLIC\".")) {
temp = temp.replace("\"PUBLIC\"."," ");
}
if(temp.contains("\"")) {
temp = temp.replace("\"","'");
}
arrList.add(temp);
}
arrList = arrList.subList(21,arrList.size());
for (String str : arrList){
strBuffer.append(str);
strBuffer.append(System.getProperty("line.separator"));
}
bufReader.close();
PrintWriter printWriter = new PrintWriter(outPath);
printWriter.write(strBuffer.toString().toCharArray());
printWriter.flush();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
5、java 字节码数组和文件的相互转换(工具类)
public class FileUtil {
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
6、excel 单元格处理
package com.lingxu.base.common.util;
import com.lingxu.base.common.constant.CommonConstant;
import com.lingxu.base.common.constant.DataTypeConstant;
import com.lingxu.base.common.exception.BussException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CellValueFormatUtil {
public static Object importFormat(String value, String parmtype, CellType cellType) throws ParseException {
Object obj = new Object();
if (parmtype.equals(DataTypeConstant.INTEGER_TYPE_NAME)) {
Double d = Double.parseDouble(value);
obj = d.intValue();
} else if (parmtype.equals(DataTypeConstant.DOUBLE_TYPE_NAME)) {
obj = Double.parseDouble(value);
} else if (parmtype.equals(DataTypeConstant.FLOAT_TYPE_NAME)) {
Double d = Double.parseDouble(value);
obj = d.floatValue();
} else if (parmtype.equals(DataTypeConstant.LONG_TYPE_NAME)) {
Double d = Double.parseDouble(value);
obj = d.longValue();
} else if (parmtype.equals(DataTypeConstant.DATE_TYPE_NAME)) {
if (cellType == CellType.NUMERIC) {
Double d = Double.parseDouble(value);
Date date = DateUtil.getJavaDate(d);
obj = date;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.TIME_FORMAT_YMDHMS);
obj = sdf.parse(value);
}
} else if (parmtype.equals(DataTypeConstant.BIGDECIMAL_TYPE_NAME)) {
BigDecimal ab = new BigDecimal(value);
obj = ab;
} else {
obj = value;
}
return obj;
}
public static String cellToString(Cell cell) {
if (cell == null) {
return null;
} else {
if (cell.getCellTypeEnum() == CellType.STRING) {
return cell.getStringCellValue();
} else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else if (cell.getCellTypeEnum() == CellType.BLANK) {
return null;
} else if (cell.getCellTypeEnum() == CellType.FORMULA) {
cell.setCellType(CellType.STRING);
return cell.getStringCellValue();
} else {
throw new BussException("Excel格式不正确");
}
}
}
}
7、文件下载相关
package com.lingxu.base.common.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
@Component
public class CompressDownloadUtil {
public HttpServletResponse setDownloadResponse(HttpServletResponse response, String downloadName) {
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName*=UTF-8''"+ downloadName);
return response;
}
public Integer[] toIntegerArray(String param) {
return Arrays.stream(param.split(","))
.map(Integer::valueOf)
.toArray(Integer[]::new);
}
public void compressZip(List<File> files, OutputStream outputStream) {
ZipOutputStream zipOutStream = null;
try {
zipOutStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
zipOutStream.setMethod(ZipOutputStream.DEFLATED);
for (int i = 0; i < files.size(); i++) {
File file = files.get(i);
FileInputStream filenputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
filenputStream.read(data);
zipOutStream.putNextEntry(new ZipEntry(i + file.getName()));
zipOutStream.write(data);
filenputStream.close();
zipOutStream.closeEntry();
}
} catch (IOException e) {
log.error("输入异常"+e.getMessage());
} finally {
try {
if (Objects.nonNull(zipOutStream)) {
zipOutStream.flush();
zipOutStream.close();
}
if (Objects.nonNull(outputStream)) {
outputStream.close();
}
} catch (IOException e) {
log.error("输入异常"+e.getMessage());
}
}
}
public HttpServletResponse downloadFile(String zipFilepath,HttpServletResponse response) {
try {
File file = new File(zipFilepath);
String filename = file.getName();
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
InputStream fis = new BufferedInputStream(new FileInputStream(zipFilepath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
response.addHeader("Access-Control-Allow-Origin","*");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
return null;
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
public void deleteFile(String filepath) {
File file = new File(filepath);
deleteFile(file);
}
public void deleteFile(File file) {
if (file.isFile() && file.exists()) {
file.delete();
}
}
}
8、文件复制,删除等
package com.lingxu.base.common.util;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Set;
public class FileUtils {
public static boolean copyDir(String src, String des) {
try {
File file1=new File(src);
if(!file1.exists()){
return false;
}else{
File[] fs=file1.listFiles();
File file2=new File(des);
if(!file2.exists()){
file2.mkdirs();
}
for (File f : fs) {
if(f.isFile()){
fileCopy(f.getPath(),des+ File.separator+f.getName());
}else if(f.isDirectory()){
copyDir(f.getPath(),des+File.separator+f.getName());
}
}
return true;
}
}catch (Exception e){
e.getStackTrace();
return false;
}
}
private static void fileCopy(String src, String des) throws Exception {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(des));
int i = -1;
byte[] bt = new byte[2014];
while ((i = bis.read(bt))!=-1) {
bos.write(bt, 0, i);
}
bis.close();
bos.close();
}
public static String getFileName(String fName){
String fileName = null;
File tempFile =new File( fName.trim());
if(tempFile.exists()){
File[] array = tempFile.listFiles();
for(int i = 0 ; i<array.length ; i++){
String houzhui = array[i].toString().substring(array[i].toString().lastIndexOf(".") + 1);
if(houzhui.equals("iw")||houzhui.equals(".zip")){
fileName = array[i].getName();
}
}
}
return fileName;
}
private static void doDeleteEmptyDir(String dir) {
boolean success = (new File(dir)).delete();
if (success) {
} else {
}
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static Set<String> getDirName(String fName){
Set<String> set = new HashSet<>();
String fileName = null;
File tempFile =new File( fName.trim());
if(tempFile.exists()){
File[] array = tempFile.listFiles();
for(int i = 0 ; i<array.length ; i++){
set.add(array[i].getName().toString());
}
}
System.out.println(set);
return set;
}
public static boolean isExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
public static boolean isDir(String path) {
File file = new File(path);
if(file.exists()){
return file.isDirectory();
}else{
return false;
}
}
public static boolean renameTo(String oldFilePath, String newName) {
try {
File oldFile = new File(oldFilePath);
if(oldFile.exists()){
if (newName.indexOf("/") < 0 && newName.indexOf("\\") < 0){
String absolutePath = oldFile.getAbsolutePath();
if(newName.indexOf("/") > 0){
newName = absolutePath.substring(0, absolutePath.lastIndexOf("/") + 1) + newName;
}else{
newName = absolutePath.substring(0, absolutePath.lastIndexOf("\\") + 1) + newName;
}
}
File file = new File(newName);
if(file.exists()){
System.out.println("该文件已存在,不能重命名");
}else{
return oldFile.renameTo(file);
}
}else {
System.out.println("原该文件不存在,不能重命名");
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void copy(String sourceFile, String targetFile) {
File source = new File(sourceFile);
File target = new File(targetFile);
target.getParentFile().mkdirs();
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel in = null;
FileChannel out = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
in = fis.getChannel();
out = fos.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null){
out.close();
}
if (in != null){
in.close();
}
if (fos != null){
fos.close();
}
if (fis != null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getSaveDir(String previousDir, String dirName) {
if (StringUtils.isNotBlank(previousDir)){
dirName = previousDir + "/" + dirName + "/";
}else {
dirName = dirName + "/";
}
return dirName;
}
public static String mkdirs(String dirPath) {
try{
File file = new File(dirPath);
if(!file.exists()){
file.mkdirs();
}
}catch(Exception e){
e.printStackTrace();
}
return dirPath;
}
public static void main(String[] args) throws Exception {
String path="E://OaTestFile/";
String name="办公室";
String endPath=path+name;
if (isExists(endPath)){
System.out.println("文件夹已存在");
}else {
mkdirs(endPath);
System.out.println("ok");
}
}
}
9、大文件下载
package com.lingxu.base.common.util;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FolderToZipUtil {
public static void zip(String sourceFileName, HttpServletResponse response){
ZipOutputStream out = null;
BufferedOutputStream bos = null;
try {
response.setHeader("content-type", "application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition",
"attachment;filename=" + new String("我是压缩后的文件".getBytes("gbk"), "iso8859-1")+".zip");
out = new ZipOutputStream(response.getOutputStream());
bos = new BufferedOutputStream(out);
File sourceFile = new File(sourceFileName);
compress(out, bos, sourceFile, sourceFile.getName());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
IOCloseUtil.close(bos, out);
}
}
public static void compress(ZipOutputStream out, BufferedOutputStream bos, File sourceFile, String base){
FileInputStream fos = null;
BufferedInputStream bis = null;
try {
if (sourceFile.isDirectory()) {
File[] flist = sourceFile.listFiles();
if (flist.length == 0) {
out.putNextEntry(new ZipEntry(base + "/"));
} else {
for (int i = 0; i < flist.length; i++) {
compress(out, bos, flist[i], base + "/" + flist[i].getName());
}
}
} else {
out.putNextEntry(new ZipEntry(base));
fos = new FileInputStream(sourceFile);
bis = new BufferedInputStream(fos);
int tag;
while ((tag = bis.read()) != -1) {
out.write(tag);
}
bis.close();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
IOCloseUtil.close(bis,fos);
}
}
}
2、http请求
1、get请求、post请求
package com.lingxu.module.BigDataJoinMessage.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.SocketTimeoutException;
@Slf4j
public class HttpClientUtilPersect {
static PoolingHttpClientConnectionManager poolingClient = null;
public static void init() {
poolingClient = new PoolingHttpClientConnectionManager();
poolingClient.setDefaultMaxPerRoute(100);
poolingClient.setMaxTotal(500);
}
public static CloseableHttpClient getHttpClient(int timeout) {
Integer CONNECTION_TIMEOUT = 2 * 1000;
Integer SO_TIMEOUT = timeout * 1000;
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setSocketTimeout(SO_TIMEOUT).build();
ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse httpResponse,
HttpContext httpContext) {
return 10000L;
}
};
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(poolingClient);
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler());
httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy);
CloseableHttpClient httpClient = httpClientBuilder.build();
return httpClient;
}
public static String doGet(String url) {
CloseableHttpClient httpClient = getHttpClient(4);
String resultString = "";
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (ConnectTimeoutException e) {
return doReapeat(httpGet);
} catch (SocketTimeoutException e) {
return doReapeat(httpGet);
} catch (Exception e) {
e.printStackTrace();
log.error("HttpClientUtil url: "+url+"+ error:{}", e);
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
log.error("HttpClientUtil url: "+url+"+ error:{}", e);
}
}
return resultString;
}
public static String doPost(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(response !=null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostJson(String url, String json,String auth)
throws Exception
{
url=url+"?auth="+auth;
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
log.info("doPostJson请求的url"+url);
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setHeader("Content-type","application/json");
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
log.info("doPostJson请求返回的json-{}"+resultString);
} catch (Exception e) {
e.printStackTrace();
log.error("请求报错-{}"+e.getMessage());
throw new Exception(e);
} finally {
try {
if(response !=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
private static String doReapeat(HttpRequestBase request){
CloseableHttpClient httpClient = getHttpClient(6);
HttpResponse response = null;
try {
response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
log.error("重发,接口请求失败,httpcode="
+ response.getStatusLine().getStatusCode() + "; url="
+ request.getURI());
return null;
}
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (Exception e) {
log.error("重发,调用API错误, url:" + request.getURI(), e);
return null;
} finally {
close(response, httpClient);
}
}
private static void close(HttpResponse response, CloseableHttpClient httpClient){
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
log.error("response close error: {}", e);
}
}
}
}
2、带请求头的get,post请求
package com.lingxu.base.common.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
public class HttpClientUtil {
public static String doGet(String httpurl, Map<String, String> headers) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpurl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (headers != null) {
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
}
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();
}
return result;
}
public static String doPost(String httpUrl, String param, Map<String, String> headers) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
if (headers != null) {
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
os = connection.getOutputStream();
os.write(param.getBytes());
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();
}
return result;
}
public static boolean saveImageToDisk(String imgUrl, String fileName, String filePath) {
InputStream inputStream = null;
inputStream = getInputStream(imgUrl);
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath + fileName);
while ((len = inputStream.read(data))!=-1) {
fileOutputStream.write(data,0,len);
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally{
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static InputStream getInputStream(String imgUrl){
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(imgUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
inputStream = httpURLConnection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}
3、工具类转换
1、object转成map
package com.lingxu.module.picture.util;
import lombok.extern.slf4j.Slf4j;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class util {
public static Map<String, Object> transBean2Map(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")) {
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
log.error("transBeanMap Error {}" ,e);
}
return map;
}
}
4、其他工具类
1、获取当前登录人的ip
参数获取
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
package com.lingxu.base.common.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
public class IPUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
return ip;
}
}
2、sha1加解密
package com.lingxu.base.common.util;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import sun.misc.BASE64Decoder;
public class AESEncryptUtil {
public static final String sha1(String text) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(text.getBytes());
byte[] messageDigest = digest.digest();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
stringBuffer.append(0);
}
stringBuffer.append(shaHex);
}
return stringBuffer.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
private static String getMd5(String text) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] md5bytes = md5.digest(text.getBytes());
return bytesToHex(md5bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
private static String bytesToHex(byte[] bytes) {
StringBuffer md5str = new StringBuffer();
int digital;
for (int i = 0; i < bytes.length; i++) {
digital = bytes[i];
if (digital < 0) {
digital += 256;
}
if (digital < 16) {
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
return md5str.toString();
}
private static String aesCBCDecrypt(String appKey, String iv, String text) {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
SecretKeySpec secretKeySpec = new SecretKeySpec(appKey.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] original = cipher.doFinal(new BASE64Decoder().decodeBuffer(text));
return new String(original);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String getCurrentTimeStamp() {
String timeStamp = System.currentTimeMillis() + "";
return timeStamp.substring(0, 10);
}
private static String sort(String[] arr) {
Arrays.sort(arr);
StringBuilder builder = new StringBuilder();
for (String s : arr) {
builder.append(s);
}
return builder.toString();
}
public static String decrypt(String appkey, String token, String signature, String timeStamp, String nonce, String text) {
timeStamp = timeStamp == null ? timeStamp = getCurrentTimeStamp() : timeStamp;
String[] arr = {token, timeStamp, nonce, text};
String sortedString = sort(arr);
String sha1String = sha1(sortedString);
if (!sha1String.equals(signature)) {
}
String iv = getMd5(appkey).substring(0, 16);
String decryptedText = aesCBCDecrypt(appkey, iv, text);
return decryptedText;
}
}
2、汉字获取字母
package com.lingxu.base.common.util;
import java.io.UnsupportedEncodingException;
public class ChineseUtil {
private final static int[] areaCode = {1601, 1637, 1833, 2078, 2274,
2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858,
4027, 4086, 4390, 4558, 4684, 4925, 5249, 5590};
private final static String[] letters = {"a", "b", "c", "d", "e",
"f", "g", "h", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "w", "x", "y", "z"};
public static String getFirstLetter(String chinese) {
if (chinese == null || chinese.trim().length() == 0) {
return "";
}
chinese = conversionStr(chinese, "GB2312", "ISO8859-1");
if (chinese.length() > 1)
{
int li_SectorCode = (int) chinese.charAt(0);
int li_PositionCode = (int) chinese.charAt(1);
li_SectorCode = li_SectorCode - 160;
li_PositionCode = li_PositionCode - 160;
int li_SecPosCode = li_SectorCode * 100 + li_PositionCode;
if (li_SecPosCode > 1600 && li_SecPosCode < 5590) {
for (int i = 0; i < 23; i++) {
if (li_SecPosCode >= areaCode[i]
&& li_SecPosCode < areaCode[i + 1]) {
chinese = letters[i];
break;
}
}
} else
{
chinese = conversionStr(chinese, "ISO8859-1", "GB2312");
chinese = chinese.substring(0, 1);
}
}
return chinese;
}
private static String conversionStr(String str, String charsetName, String toCharsetName) {
try {
str = new String(str.getBytes(charsetName), toCharsetName);
} catch (UnsupportedEncodingException ex) {
System.out.println("字符串编码转换异常:" + ex.getMessage());
}
return str;
}
}
3、密码加盐,加解密方法
package com.lingxu.base.common.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Key;
import java.security.SecureRandom;
public class PasswordUtil {
public static final String ALGORITHM = "PBEWithMD5AndDES";
public static final String Salt = "63293188";
private static final int ITERATIONCOUNT = 1000;
public static byte[] getSalt() throws Exception {
SecureRandom random = new SecureRandom();
return random.generateSeed(8);
}
public static byte[] getStaticSalt() {
return Salt.getBytes();
}
private static Key getPBEKey(String password) {
SecretKeyFactory keyFactory;
SecretKey secretKey = null;
try {
keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return secretKey;
}
public static String encrypt(String plaintext, String password, String salt) {
Key key = getPBEKey(password);
byte[] encipheredData = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
encipheredData = cipher.doFinal(plaintext.getBytes("utf-8"));
} catch (Exception e) {
}
return bytesToHexString(encipheredData);
}
public static String decrypt(String ciphertext, String password, String salt) {
Key key = getPBEKey(password);
byte[] passDec = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
passDec = cipher.doFinal(hexStringToBytes(ciphertext));
}
catch (Exception e) {
}
return new String(passDec);
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
4、redis 工具类
package com.lingxu.base.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean setDay(String key, Object value, int days) {
try {
if (days > 0) {
redisTemplate.opsForValue().set(key, value, days, TimeUnit.DAYS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Long rPush(String key, Object value){
try {
return redisTemplate.opsForList().rightPush(key,value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
5、数据库连接加解密SM2
package com.lingxu.base.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Properties;
@Slf4j
public class SM2DbConnUtil {
private static String dbConnPrivateKey;
private static String dbConnPublicKey;
private static Properties prop = new Properties();
private static SM2Engine sm2EncryptEngine;
private static SM2Engine sm2DecryptEngine;
static{
readProperties("key.properties");
dbConnPrivateKey=prop.getProperty("dbConnPrivateKey");
dbConnPublicKey=prop.getProperty("dbConnPublicKey");
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
sm2ECParameters.getG(), sm2ECParameters.getN());
ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(hexString2byte(dbConnPublicKey));
ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);
sm2EncryptEngine = new SM2Engine();
sm2EncryptEngine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));
BigInteger privateKeyD = new BigInteger(dbConnPrivateKey, 16);
ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
sm2DecryptEngine = new SM2Engine();
sm2DecryptEngine.init(false, privateKeyParameters);
}
public static void main(String args[]){
String msg="测试加解密";
String msg1=encrypt("测试加解密");
System.out.println(msg1);
String msg2=decrypt(msg1);
System.out.println(msg2);
}
public static void createKeyPair() throws NoSuchAlgorithmException {
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
keyPairGenerator.init(new ECKeyGenerationParameters(domainParameters, SecureRandom.getInstance("SHA1PRNG")));
AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();
BigInteger privatekey = ((ECPrivateKeyParameters) asymmetricCipherKeyPair.getPrivate()).getD();
String privateKeyHex = privatekey.toString(16);
System.out.println("privateKeyHex: "+privateKeyHex);
ECPoint ecPoint = ((ECPublicKeyParameters) asymmetricCipherKeyPair.getPublic()).getQ();
String publicKeyHex = Hex.toHexString(ecPoint.getEncoded(false));
System.out.println("publicKeyHex: "+publicKeyHex);
}
public static void readProperties(String fileName){
try {
InputStream in = PropertiesUtil.class.getResourceAsStream("/"+fileName);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
prop.load(bf);
}catch (IOException e){
e.printStackTrace();
}
}
public static String encrypt(String data){
byte[] arrayOfBytes = null;
try {
byte[] in = data.getBytes("utf-8");
byte[] in2 = Base64.getEncoder().encode(in);
arrayOfBytes = sm2EncryptEngine.processBlock(in2, 0, in2.length);
} catch (Exception e) {
log.error("SM2加密时出现异常:", e);
}
return Hex.toHexString(arrayOfBytes);
}
public static String decrypt(String cipherData) {
byte[] cipherDataByte = Hex.decode(cipherData);
String result = null;
try {
byte[] arrayOfBytes = Base64.getDecoder().decode(sm2DecryptEngine.processBlock(cipherDataByte, 0, cipherDataByte.length));
return new String(arrayOfBytes, "utf-8");
} catch (Exception e) {
log.error("SM2解密时出现异常:", e);
}
return result;
}
public static byte[] hexString2byte(String hexString) {
if (null == hexString || hexString.length() % 2 != 0 || hexString.contains("null")) {
return null;
}
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < hexString.length(); i += 2) {
bytes[i / 2] = (byte) (Integer.parseInt(hexString.substring(i, i + 2), 16) & 0xff);
}
return bytes;
}
}
6、访问参数加解密SM2
package com.lingxu.base.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Properties;
@Slf4j
@Component
public class SM2RequestUtil {
private static String servicePrivateKey;
private static String servicePublicKey;
private static Properties prop = new Properties();
private static SM2Engine sm2EncryptEngine;
private static SM2Engine sm2DecryptEngine;
static{
readProperties("key.properties");
servicePrivateKey=prop.getProperty("servicePrivateKey");
servicePublicKey=prop.getProperty("servicePublicKey");
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
sm2ECParameters.getG(), sm2ECParameters.getN());
ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(hexString2byte(servicePublicKey));
ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);
sm2EncryptEngine = new SM2Engine();
sm2EncryptEngine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));
BigInteger privateKeyD = new BigInteger(servicePrivateKey, 16);
ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
sm2DecryptEngine = new SM2Engine();
sm2DecryptEngine.init(false, privateKeyParameters);
}
public static void main(String args[]){
String msg="测试加解密";
String msg1=encrypt("测试加解密");
System.out.println(msg1);
String msg2=decrypt(msg1);
System.out.println(msg2);
}
public static void createKeyPair() throws NoSuchAlgorithmException {
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
keyPairGenerator.init(new ECKeyGenerationParameters(domainParameters, SecureRandom.getInstance("SHA1PRNG")));
AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();
BigInteger privatekey = ((ECPrivateKeyParameters) asymmetricCipherKeyPair.getPrivate()).getD();
String privateKeyHex = privatekey.toString(16);
System.out.println("privateKeyHex: "+privateKeyHex);
ECPoint ecPoint = ((ECPublicKeyParameters) asymmetricCipherKeyPair.getPublic()).getQ();
String publicKeyHex = Hex.toHexString(ecPoint.getEncoded(false));
System.out.println("publicKeyHex: "+publicKeyHex);
}
public static void readProperties(String fileName){
try {
InputStream in = PropertiesUtil.class.getResourceAsStream("/"+fileName);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
prop.load(bf);
}catch (IOException e){
e.printStackTrace();
}
}
public static String encrypt(String data){
byte[] arrayOfBytes = null;
try {
byte[] in = data.getBytes("utf-8");
byte[] in2 = Base64.getEncoder().encode(in);
arrayOfBytes = sm2EncryptEngine.processBlock(in2, 0, in2.length);
} catch (Exception e) {
log.error("SM2加密时出现异常:", e);
}
return Hex.toHexString(arrayOfBytes);
}
public static String decrypt(String cipherData) {
byte[] cipherDataByte = Hex.decode(cipherData);
String result = null;
try {
byte[] arrayOfBytes = Base64.getDecoder().decode(sm2DecryptEngine.processBlock(cipherDataByte, 0, cipherDataByte.length));
return new String(arrayOfBytes, "utf-8");
} catch (Exception e) {
log.error("SM2解密时出现异常:", e);
}
return result;
}
public static byte[] hexString2byte(String hexString) {
if (null == hexString || hexString.length() % 2 != 0 || hexString.contains("null")) {
return null;
}
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < hexString.length(); i += 2) {
bytes[i / 2] = (byte) (Integer.parseInt(hexString.substring(i, i + 2), 16) & 0xff);
}
return bytes;
}
}
7、spring 上下文对象实例
package com.lingxu.base.common.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static String getDomain(){
HttpServletRequest request = getHttpServletRequest();
StringBuffer url = request.getRequestURL();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
}
public static String getOrigin(){
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
陆续更新中…
|