mirror of
https://gitee.com/egzosn/pay-java-parent.git
synced 2026-05-08 03:56:48 +08:00
代码优化
This commit is contained in:
@@ -150,7 +150,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
|
||||
*/
|
||||
@Override
|
||||
public <O extends PayOrder> String toPay(O order) {
|
||||
Map orderInfo = orderInfo(order);
|
||||
Map<String, Object> orderInfo = orderInfo(order);
|
||||
return buildRequest(orderInfo, MethodType.POST);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ import java.net.URLEncoder;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.egzosn.pay.common.bean.result.PayException;
|
||||
import com.egzosn.pay.common.exception.PayErrorException;
|
||||
@@ -12,13 +15,17 @@ import com.egzosn.pay.common.exception.PayErrorException;
|
||||
/**
|
||||
* URL表达式处理器
|
||||
*
|
||||
* @author: egan
|
||||
* @author egan
|
||||
* <pre>
|
||||
* email egzosn@gmail.com
|
||||
* date 2017/3/5 10:07
|
||||
* </pre>
|
||||
*/
|
||||
public class UriVariables {
|
||||
public final class UriVariables {
|
||||
private static final Log LOG = LogFactory.getLog(UriVariables.class);
|
||||
|
||||
private UriVariables() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 依次匹配
|
||||
@@ -96,26 +103,21 @@ public class UriVariables {
|
||||
if (o instanceof List) {
|
||||
o = ((List) o).toArray();
|
||||
}
|
||||
try {
|
||||
if (o instanceof Object[]) {
|
||||
Object[] os = (Object[]) o;
|
||||
String valueStr = "";
|
||||
for (int i = 0, len = os.length; i < len; i++) {
|
||||
if (null == os[i]) {
|
||||
continue;
|
||||
}
|
||||
String value = os[i].toString().trim();
|
||||
valueStr += (i == len - 1) ? value : value + ",";
|
||||
if (o instanceof Object[]) {
|
||||
Object[] os = (Object[]) o;
|
||||
String valueStr = "";
|
||||
for (int i = 0, len = os.length; i < len; i++) {
|
||||
if (null == os[i]) {
|
||||
continue;
|
||||
}
|
||||
builder.append(entry.getKey()).append("=").append(URLEncoder.encode(valueStr, "utf-8")).append("&");
|
||||
|
||||
continue;
|
||||
String value = os[i].toString().trim();
|
||||
valueStr += (i == len - 1) ? value : value + ",";
|
||||
}
|
||||
builder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(), "utf-8")).append("&");
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
builder.append(entry.getKey()).append("=").append(urlEncoder(valueStr)).append("&");
|
||||
continue;
|
||||
}
|
||||
builder.append(entry.getKey()).append("=").append(urlEncoder(entry.getValue().toString())).append("&");
|
||||
|
||||
}
|
||||
if (builder.length() > 1) {
|
||||
builder.deleteCharAt(builder.length() - 1);
|
||||
@@ -202,5 +204,19 @@ public class UriVariables {
|
||||
}
|
||||
}
|
||||
|
||||
public static String urlEncoder(String str) {
|
||||
return urlEncoder(str, "utf-8");
|
||||
}
|
||||
|
||||
public static String urlEncoder(String str, String enc) {
|
||||
try {
|
||||
return URLEncoder.encode(str, enc);
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package com.egzosn.pay.common.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* 日期转换运算工具
|
||||
@@ -19,11 +22,11 @@ import java.util.*;
|
||||
* </pre>
|
||||
*/
|
||||
public final class DateUtils {
|
||||
private static final Log LOG = LogFactory.getLog(DateUtils.class);
|
||||
|
||||
private DateUtils() {
|
||||
}
|
||||
|
||||
private static final Log LOG = LogFactory.getLog(DateUtils.class);
|
||||
|
||||
static final class DateFormatHolder {
|
||||
private static final ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>> THREADLOCAL_FORMATS = new ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>>();
|
||||
|
||||
@@ -76,7 +79,8 @@ public final class DateUtils {
|
||||
SimpleDateFormat formatFor = DateFormatHolder.formatFor(pattern);
|
||||
try {
|
||||
return formatFor.parse(date);
|
||||
} catch (ParseException e) {
|
||||
}
|
||||
catch (ParseException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
package com.egzosn.pay.common.util;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.MultiFormatWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -13,10 +7,18 @@ import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.MultiFormatWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成工具
|
||||
* @author egan
|
||||
*
|
||||
* @author egan
|
||||
* <pre>
|
||||
* email egzosn@gmail.com
|
||||
* date 2017/2/7 10:35
|
||||
@@ -25,104 +27,111 @@ import java.util.Map;
|
||||
public class MatrixToImageWriter {
|
||||
|
||||
|
||||
private static final int BLACK = 0xFF000000;
|
||||
private static final int WHITE = 0xFFFFFFFF;
|
||||
|
||||
private MatrixToImageWriter() {}
|
||||
private static final int BLACK = 0xFF000000;
|
||||
private static final int WHITE = 0xFFFFFFFF;
|
||||
|
||||
private MatrixToImageWriter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据二维矩阵的碎片 生成对应的二维码图像缓冲
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @see com.google.zxing.common.BitMatrix
|
||||
* @return 二维码图像缓冲
|
||||
* 根据二维矩阵的碎片 生成对应的二维码图像缓冲
|
||||
*
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @return 二维码图像缓冲
|
||||
* @see com.google.zxing.common.BitMatrix
|
||||
*/
|
||||
public static BufferedImage toBufferedImage(BitMatrix matrix) {
|
||||
int width = matrix.getWidth();
|
||||
int height = matrix.getHeight();
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
public static BufferedImage toBufferedImage(BitMatrix matrix) {
|
||||
int width = matrix.getWidth();
|
||||
int height = matrix.getHeight();
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成文件
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @param format 格式
|
||||
* @param file 保持的文件地址
|
||||
* @throws IOException 文件保存异常
|
||||
*/
|
||||
public static void writeToFile(BitMatrix matrix, String format, File file)
|
||||
throws IOException {
|
||||
BufferedImage image = toBufferedImage(matrix);
|
||||
if (!ImageIO.write(image, format, file)) {
|
||||
throw new IOException("Could not write an image of format " + format + " to " + file);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 二维码生成文件
|
||||
*
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @param format 格式
|
||||
* @param file 保持的文件地址
|
||||
* @throws IOException 文件保存异常
|
||||
*/
|
||||
public static void writeToFile(BitMatrix matrix, String format, File file)
|
||||
throws IOException {
|
||||
BufferedImage image = toBufferedImage(matrix);
|
||||
if (!ImageIO.write(image, format, file)) {
|
||||
throw new IOException("Could not write an image of format " + format + " to " + file);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成流
|
||||
*
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @param format 格式
|
||||
* @param stream 保持的文件输出流
|
||||
* @throws IOException 文件保存异常
|
||||
*/
|
||||
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
|
||||
throws IOException {
|
||||
BufferedImage image = toBufferedImage(matrix);
|
||||
if (!ImageIO.write(image, format, stream)) {
|
||||
throw new IOException("Could not write an image of format " + format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码信息写成JPG文件
|
||||
*
|
||||
* @param content 二维码信息
|
||||
* @param fileUrl 文件地址
|
||||
*/
|
||||
public static void writeInfoToJpgFile(String content, String fileUrl) {
|
||||
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
|
||||
Map hints = new HashMap();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
try {
|
||||
BitMatrix bitMatrix = multiFormatWriter.encode(content,
|
||||
BarcodeFormat.QR_CODE, 250, 250, hints);
|
||||
File file1 = new File(fileUrl);
|
||||
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码信息写成JPG BufferedImage
|
||||
*
|
||||
* @param content 二维码信息
|
||||
* @return JPG BufferedImage
|
||||
*/
|
||||
public static BufferedImage writeInfoToJpgBuff(String content) {
|
||||
BufferedImage re = null;
|
||||
|
||||
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
|
||||
Map hints = new HashMap();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
try {
|
||||
BitMatrix bitMatrix = multiFormatWriter.encode(content,
|
||||
BarcodeFormat.QR_CODE, 250, 250, hints);
|
||||
re = MatrixToImageWriter.toBufferedImage(bitMatrix);
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码生成流
|
||||
* @param matrix 二维矩阵的碎片 包含 宽高 行,字节
|
||||
* @param format 格式
|
||||
* @param stream 保持的文件输出流
|
||||
* @throws IOException 文件保存异常
|
||||
*/
|
||||
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
|
||||
throws IOException {
|
||||
BufferedImage image = toBufferedImage(matrix);
|
||||
if (!ImageIO.write(image, format, stream)) {
|
||||
throw new IOException("Could not write an image of format " + format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码信息写成JPG文件
|
||||
* @param content 二维码信息
|
||||
* @param fileUrl 文件地址
|
||||
*/
|
||||
public static void writeInfoToJpgFile(String content, String fileUrl){
|
||||
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
|
||||
Map hints = new HashMap();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
try {
|
||||
BitMatrix bitMatrix = multiFormatWriter.encode(content,
|
||||
BarcodeFormat.QR_CODE, 250, 250, hints);
|
||||
File file1 = new File(fileUrl);
|
||||
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 二维码信息写成JPG BufferedImage
|
||||
* @param content 二维码信息
|
||||
* @return JPG BufferedImage
|
||||
*/
|
||||
public static BufferedImage writeInfoToJpgBuff(String content){
|
||||
BufferedImage re=null;
|
||||
|
||||
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
|
||||
Map hints = new HashMap();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
try {
|
||||
BitMatrix bitMatrix = multiFormatWriter.encode(content,
|
||||
BarcodeFormat.QR_CODE, 250, 250, hints);
|
||||
re=MatrixToImageWriter.toBufferedImage(bitMatrix);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
package com.egzosn.pay.common.util;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.egzosn.pay.common.bean.result.PayException;
|
||||
import com.egzosn.pay.common.exception.PayErrorException;
|
||||
import com.egzosn.pay.common.util.str.StringUtils;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
@@ -22,20 +19,25 @@ import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.egzosn.pay.common.bean.result.PayException;
|
||||
import com.egzosn.pay.common.exception.PayErrorException;
|
||||
import com.egzosn.pay.common.util.str.StringUtils;
|
||||
|
||||
|
||||
/**
|
||||
* XML工具
|
||||
*
|
||||
* @author egan
|
||||
* <pre>
|
||||
* <pre>
|
||||
* email egzosn@gmail.com
|
||||
* date 2016-6-2 19:45:06
|
||||
* </pre>
|
||||
@@ -57,7 +59,8 @@ public class XML {
|
||||
|
||||
try {
|
||||
return (JSONObject) inputStream2Map(in, null);
|
||||
} catch (IOException e) {
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new PayErrorException(new PayException("IOException", e.getMessage()));
|
||||
}
|
||||
|
||||
@@ -76,6 +79,7 @@ public class XML {
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析xml并转化为Json值
|
||||
*
|
||||
@@ -90,6 +94,7 @@ public class XML {
|
||||
}
|
||||
return toJSONObject(content.getBytes(charset));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析xml并转化为Json值
|
||||
*
|
||||
@@ -103,7 +108,8 @@ public class XML {
|
||||
}
|
||||
try (InputStream in = new ByteArrayInputStream(content)) {
|
||||
return (JSONObject) inputStream2Map(in, null);
|
||||
} catch (IOException e) {
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new PayErrorException(new PayException("IOException", e.getMessage()));
|
||||
}
|
||||
|
||||
@@ -113,8 +119,8 @@ public class XML {
|
||||
* 解析xml并转化为Json值
|
||||
*
|
||||
* @param content json字符串
|
||||
* @param clazz 需要转化的类
|
||||
* @param <T> 返回对应类型
|
||||
* @param clazz 需要转化的类
|
||||
* @param <T> 返回对应类型
|
||||
* @return Json值
|
||||
*/
|
||||
public static <T> T toBean(String content, Class<T> clazz) {
|
||||
@@ -124,7 +130,8 @@ public class XML {
|
||||
}
|
||||
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))) {
|
||||
return inputStream2Bean(in, clazz);
|
||||
} catch (IOException e) {
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new PayErrorException(new PayException("IOException", e.getMessage()));
|
||||
}
|
||||
|
||||
@@ -154,7 +161,8 @@ public class XML {
|
||||
JSONArray array = new JSONArray();
|
||||
array.add(json);
|
||||
json = array;
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
j.put(node.getNodeName(), getChildren(nodeList));
|
||||
}
|
||||
}
|
||||
@@ -164,7 +172,8 @@ public class XML {
|
||||
c.put(node.getNodeName(), getChildren(nodeList));
|
||||
((JSONArray) json).add(c);
|
||||
}
|
||||
} else if (node.getNodeType() == Node.ELEMENT_NODE ) {
|
||||
}
|
||||
else if (node.getNodeType() == Node.ELEMENT_NODE) {
|
||||
if (null == json) {
|
||||
json = new JSONObject();
|
||||
}
|
||||
@@ -224,22 +233,27 @@ public class XML {
|
||||
Node node = children.item(idx);
|
||||
NodeList nodeList = node.getChildNodes();
|
||||
int length = nodeList.getLength();
|
||||
if (node.getNodeType() == Node.ELEMENT_NODE && (length >1 || length==1 && nodeList.item(0).hasChildNodes())) {
|
||||
if (node.getNodeType() == Node.ELEMENT_NODE && (length > 1 || length == 1 && nodeList.item(0).hasChildNodes())) {
|
||||
m.put(node.getNodeName(), getChildren(nodeList));
|
||||
} else if (node.getNodeType() == Node.ELEMENT_NODE ) {
|
||||
}
|
||||
else if (node.getNodeType() == Node.ELEMENT_NODE) {
|
||||
m.put(node.getNodeName(), node.getTextContent());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
catch (ParserConfigurationException e) {
|
||||
throw new PayErrorException(new PayException("XML failure", "XML解析失败\n" + e.getMessage()));
|
||||
} finally {
|
||||
}
|
||||
catch (SAXException e) {
|
||||
throw new PayErrorException(new PayException("XML failure", "XML解析失败\n" + e.getMessage()));
|
||||
}
|
||||
finally {
|
||||
in.close();
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 将Map转换为XML格式的字符串
|
||||
*
|
||||
@@ -254,16 +268,17 @@ public class XML {
|
||||
/**
|
||||
* 将Map转换为XML格式的字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param data Map类型数据
|
||||
* @param rootElementName 最外层节点名称
|
||||
* @param encoding 字符编码
|
||||
* @param encoding 字符编码
|
||||
* @return XML格式的字符串
|
||||
*/
|
||||
public static String getMap2Xml(Map<String, Object> data, String rootElementName, String encoding) {
|
||||
Document document = null;
|
||||
try {
|
||||
document = newDocument();
|
||||
} catch (ParserConfigurationException e) {
|
||||
}
|
||||
catch (ParserConfigurationException e) {
|
||||
throw new PayErrorException(new PayException("ParserConfigurationException", e.getLocalizedMessage()));
|
||||
}
|
||||
org.w3c.dom.Element root = document.createElement(rootElementName);
|
||||
@@ -292,18 +307,18 @@ public class XML {
|
||||
transformer.transform(source, result);
|
||||
String output = writer.getBuffer().toString();
|
||||
return output;
|
||||
} catch (TransformerException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (TransformerException e) {
|
||||
throw new PayErrorException(new PayException("XML failure", "XML生成失败\n" + e.getMessage()));
|
||||
}
|
||||
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 将Map转换为XML格式的字符串
|
||||
*
|
||||
* @param data Map类型数据
|
||||
* @param data Map类型数据
|
||||
* @param document 文档
|
||||
* @param element 节点
|
||||
*/
|
||||
@@ -333,17 +348,19 @@ public class XML {
|
||||
}
|
||||
}
|
||||
|
||||
private static void object2Xml(Object value, Document document, org.w3c.dom.Element element){
|
||||
private static void object2Xml(Object value, Document document, org.w3c.dom.Element element) {
|
||||
|
||||
if (value instanceof Map){
|
||||
map2Xml((Map)value, document, element);
|
||||
}else if (value instanceof List){
|
||||
List vs = (List)value;
|
||||
for (Object v : vs ){
|
||||
if (value instanceof Map) {
|
||||
map2Xml((Map) value, document, element);
|
||||
}
|
||||
else if (value instanceof List) {
|
||||
List vs = (List) value;
|
||||
for (Object v : vs) {
|
||||
object2Xml(v, document, element);
|
||||
}
|
||||
// map2Xml((Map)value, document, element);
|
||||
}else {
|
||||
}
|
||||
else {
|
||||
value = value.toString().trim();
|
||||
element.appendChild(document.createTextNode(value.toString()));
|
||||
}
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
package com.egzosn.pay.common.util.sign;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.egzosn.pay.common.bean.result.PayException;
|
||||
import com.egzosn.pay.common.exception.PayErrorException;
|
||||
import com.egzosn.pay.common.util.sign.encrypt.sm3.SM3Digest;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
|
||||
public class SecureUtil {
|
||||
//日志
|
||||
protected static final Log log = LogFactory.getLog(SecureUtil.class);
|
||||
|
||||
private static final Log LOG = LogFactory.getLog(SecureUtil.class);
|
||||
/**
|
||||
* 算法常量: SHA1
|
||||
*/
|
||||
@@ -34,19 +36,20 @@ public class SecureUtil {
|
||||
/**
|
||||
* 获取摘要
|
||||
*
|
||||
* @param data 待计算的数据
|
||||
* @param data 待计算的数据
|
||||
* @param algorithm 算法名
|
||||
* @return 计算结果
|
||||
*/
|
||||
private static byte[] digestByData (byte[] data,String algorithm) {
|
||||
private static byte[] digestByData(byte[] data, String algorithm) {
|
||||
MessageDigest md = null;
|
||||
try {
|
||||
md = MessageDigest.getInstance(algorithm);
|
||||
md.reset();
|
||||
md.update(data);
|
||||
return md.digest();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (NoSuchAlgorithmException e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -58,7 +61,7 @@ public class SecureUtil {
|
||||
* @param encoding 编码
|
||||
* @return 计算结果
|
||||
*/
|
||||
public static byte[] sha1X16 (String data, String encoding) {
|
||||
public static byte[] sha1X16(String data, String encoding) {
|
||||
try {
|
||||
byte[] bytes = digestByData(data.getBytes(encoding), ALGORITHM_SHA1);
|
||||
StringBuilder sha1StrBuff = new StringBuilder();
|
||||
@@ -66,41 +69,42 @@ public class SecureUtil {
|
||||
if (Integer.toHexString(0xFF & bytes[i]).length() == 1) {
|
||||
sha1StrBuff.append("0").append(
|
||||
Integer.toHexString(0xFF & bytes[i]));
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
sha1StrBuff.append(Integer.toHexString(0xFF & bytes[i]));
|
||||
}
|
||||
}
|
||||
return sha1StrBuff.toString().getBytes(encoding);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* sha256计算后进行16进制转换
|
||||
*
|
||||
* @param data
|
||||
* 待计算的数据
|
||||
* @param encoding
|
||||
* 编码
|
||||
* @param data 待计算的数据
|
||||
* @param encoding 编码
|
||||
* @return 计算结果
|
||||
*/
|
||||
public static String sha256X16Str(String data, String encoding) {
|
||||
byte[] bytes =null;
|
||||
byte[] bytes = null;
|
||||
try {
|
||||
bytes = digestByData(data.getBytes(encoding), ALGORITHM_SHA1);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new PayErrorException(new PayException("error", e.getLocalizedMessage()));
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
throw new PayErrorException(new PayException("error", e.getLocalizedMessage()));
|
||||
}
|
||||
StringBuilder sha256StrBuff = new StringBuilder();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
if (Integer.toHexString(0xFF & bytes[i]).length() == 1) {
|
||||
sha256StrBuff.append("0").append(
|
||||
Integer.toHexString(0xFF & bytes[i]));
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
sha256StrBuff.append(Integer.toHexString(0xFF & bytes[i]));
|
||||
}
|
||||
}
|
||||
@@ -110,8 +114,7 @@ public class SecureUtil {
|
||||
/**
|
||||
* SM3计算.
|
||||
*
|
||||
* @param data
|
||||
* 待计算的数据
|
||||
* @param data 待计算的数据
|
||||
* @return 计算结果
|
||||
*/
|
||||
private static byte[] sm3(byte[] data) {
|
||||
@@ -126,25 +129,25 @@ public class SecureUtil {
|
||||
/**
|
||||
* sm3计算后进行16进制转换
|
||||
*
|
||||
* @param data
|
||||
* 待计算的数据
|
||||
* @param encoding
|
||||
* 编码
|
||||
* @param data 待计算的数据
|
||||
* @param encoding 编码
|
||||
* @return 计算结果
|
||||
*/
|
||||
public static String sm3X16Str(String data, String encoding) {
|
||||
byte[] bytes = new byte[new SM3Digest().getDigestSize()];
|
||||
try {
|
||||
bytes = SecureUtil.sm3(data.getBytes(encoding));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
StringBuilder sm3StrBuff = new StringBuilder();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
if (Integer.toHexString(0xFF & bytes[i]).length() == 1) {
|
||||
sm3StrBuff.append("0").append(
|
||||
Integer.toHexString(0xFF & bytes[i]));
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
sm3StrBuff.append(Integer.toHexString(0xFF & bytes[i]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,35 @@
|
||||
package com.egzosn.pay.common.util.sign;
|
||||
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
|
||||
import com.egzosn.pay.common.bean.SignType;
|
||||
import com.egzosn.pay.common.bean.result.PayException;
|
||||
import com.egzosn.pay.common.exception.PayErrorException;
|
||||
import com.egzosn.pay.common.util.str.StringUtils;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 签名 工具
|
||||
*
|
||||
* @author: egan
|
||||
* @author egan
|
||||
* <pre>
|
||||
* email egzosn@gmail.com
|
||||
* date 2016/11/9 17:45
|
||||
@@ -51,7 +63,7 @@ public enum SignUtils implements SignType {
|
||||
public boolean verify(String text, String sign, String key, String characterEncoding) {
|
||||
return com.egzosn.pay.common.util.sign.encrypt.MD5.verify(text, sign, key, characterEncoding);
|
||||
}
|
||||
},HMACSHA256{
|
||||
}, HMACSHA256 {
|
||||
@Override
|
||||
public String getName() {
|
||||
return "HMAC-SHA256";
|
||||
@@ -79,12 +91,15 @@ public enum SignUtils implements SignType {
|
||||
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
|
||||
}
|
||||
return sb.toString().toUpperCase();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeyException e) {
|
||||
e.printStackTrace();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (NoSuchAlgorithmException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (InvalidKeyException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
|
||||
throw new PayErrorException(new PayException("fail", "HMACSHA256 签名异常"));
|
||||
@@ -162,10 +177,11 @@ public enum SignUtils implements SignType {
|
||||
return com.egzosn.pay.common.util.sign.encrypt.RSA2.verify(text, sign, publicKey, characterEncoding);
|
||||
}
|
||||
};
|
||||
private static final Log LOG = LogFactory.getLog(SignUtils.class);
|
||||
|
||||
/**
|
||||
*
|
||||
* 把数组所有元素排序,并按照“参数=参数值”的模式用“@param separator”字符拼接成字符串
|
||||
*
|
||||
* @param parameters 参数
|
||||
* @return 去掉空值与签名参数后的新签名,拼接后字符串
|
||||
*/
|
||||
@@ -175,10 +191,10 @@ public enum SignUtils implements SignType {
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 把数组所有元素排序,并按照“参数=参数值”的模式用“@param separator”字符拼接成字符串
|
||||
*
|
||||
* @param parameters 参数
|
||||
* @param separator 分隔符
|
||||
* @param separator 分隔符
|
||||
* @return 去掉空值与签名参数后的新签名,拼接后字符串
|
||||
*/
|
||||
public static String parameterText(Map parameters, String separator) {
|
||||
@@ -186,42 +202,47 @@ public enum SignUtils implements SignType {
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 把数组所有元素排序,并按照“参数=参数值”的模式用“@param separator”字符拼接成字符串
|
||||
*
|
||||
* @param parameters 参数
|
||||
* @param separator 分隔符
|
||||
* @param ignoreKey 需要忽略添加的key
|
||||
* @param separator 分隔符
|
||||
* @param ignoreKey 需要忽略添加的key
|
||||
* @return 去掉空值与签名参数后的新签名,拼接后字符串
|
||||
*/
|
||||
public static String parameterText(Map parameters, String separator, String... ignoreKey) {
|
||||
public static String parameterText(Map<String, Object> parameters, String separator, String... ignoreKey) {
|
||||
return parameterText(parameters, separator, true, ignoreKey);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 把数组所有元素排序,并按照“参数=参数值”的模式用“@param separator”字符拼接成字符串
|
||||
* @param parameters 参数
|
||||
* @param separator 分隔符
|
||||
*
|
||||
* @param parameters 参数
|
||||
* @param separator 分隔符
|
||||
* @param ignoreNullValue 需要忽略NULL值
|
||||
* @param ignoreKey 需要忽略添加的key
|
||||
* @param ignoreKey 需要忽略添加的key
|
||||
* @return 去掉空值与签名参数后的新签名,拼接后字符串
|
||||
*/
|
||||
public static String parameterText(Map parameters, String separator, boolean ignoreNullValue, String... ignoreKey ) {
|
||||
if(parameters == null){
|
||||
public static String parameterText(Map<String, Object> parameters, String separator, boolean ignoreNullValue, String... ignoreKey) {
|
||||
if (parameters == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (null != ignoreKey){
|
||||
|
||||
if (null != ignoreKey) {
|
||||
Arrays.sort(ignoreKey);
|
||||
}
|
||||
StringBuffer sb = new StringBuffer();
|
||||
// TODO 2016/11/11 10:14 author: egan 已经排序好处理
|
||||
if (parameters instanceof SortedMap) {
|
||||
for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>)parameters.entrySet()) {
|
||||
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
|
||||
Object v = entry.getValue();
|
||||
if (null == v || "".equals(v.toString().trim()) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, entry.getKey() ) >= 0)) {
|
||||
if (null == v) {
|
||||
continue;
|
||||
}
|
||||
sb.append(entry.getKey() ).append("=").append( v.toString().trim()).append(separator);
|
||||
String valStr = v.toString().trim();
|
||||
if ("".equals(valStr) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, entry.getKey()) >= 0)) {
|
||||
continue;
|
||||
}
|
||||
sb.append(entry.getKey()).append("=").append(valStr).append(separator);
|
||||
}
|
||||
if (sb.length() > 0 && !"".equals(separator)) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
@@ -230,7 +251,13 @@ public enum SignUtils implements SignType {
|
||||
|
||||
}
|
||||
|
||||
return sortMapParameterText(parameters, separator, ignoreNullValue, ignoreKey);
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static String sortMapParameterText(Map<String, Object> parameters, String separator, boolean ignoreNullValue, String... ignoreKey) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
// TODO 2016/11/11 10:14 author: egan 未排序须处理
|
||||
List<String> keys = new ArrayList<String>(parameters.keySet());
|
||||
//排序
|
||||
@@ -246,16 +273,19 @@ public enum SignUtils implements SignType {
|
||||
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
String value = values[i].trim();
|
||||
if ("".equals(value)){ continue;}
|
||||
valueStr += (i == values.length - 1) ? value : value + ",";
|
||||
if ("".equals(value)) {
|
||||
continue;
|
||||
}
|
||||
valueStr += (i == values.length - 1) ? value : value + ",";
|
||||
}
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
valueStr = o.toString();
|
||||
}
|
||||
if (null == valueStr || "".equals(valueStr.toString().trim()) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, k ) >= 0)) {
|
||||
if (StringUtils.isBlank(valueStr) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, k) >= 0)) {
|
||||
continue;
|
||||
}
|
||||
sb.append(k ).append("=").append( valueStr).append(separator);
|
||||
sb.append(k).append("=").append(valueStr).append(separator);
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
@@ -266,35 +296,38 @@ public enum SignUtils implements SignType {
|
||||
/**
|
||||
* 将参数集合(事前做好排序)按分割符号拼凑字符串并加密为MD5
|
||||
* example: mchnt_cd+"|" +order_id+"|"+order_amt+"|"+order_pay_type+"|"+page_notify_url+"|"+back_notify_url+"|"+order_valid_time+"|"+iss_ins_cd+"|"+goods_name+"|"+"+goods_display_url+"|"+rem+"|"+ver+"|"+mchnt_key
|
||||
*
|
||||
* @param parameters 参数集合
|
||||
* @param separator 分隔符
|
||||
* @param separator 分隔符
|
||||
* @return 参数排序好的值
|
||||
*/
|
||||
public static String parameters2MD5Str(Object parameters, String separator){
|
||||
public static String parameters2Md5Str(Object parameters, String separator) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
if (parameters instanceof LinkedHashMap) {
|
||||
Set<String > keys = (Set<String>) ((LinkedHashMap)parameters).keySet();
|
||||
for(String key : keys){
|
||||
String val = ((LinkedHashMap)parameters).get(key).toString();
|
||||
Set<String> keys = (Set<String>) ((LinkedHashMap) parameters).keySet();
|
||||
for (String key : keys) {
|
||||
String val = ((LinkedHashMap) parameters).get(key).toString();
|
||||
sb.append(val).append(separator);
|
||||
|
||||
}
|
||||
}else if(parameters instanceof List){
|
||||
for(BasicNameValuePair bnv :((List<BasicNameValuePair>)parameters) ){
|
||||
sb.append(bnv.getValue()).append(separator);
|
||||
}
|
||||
else if (parameters instanceof List) {
|
||||
for (BasicNameValuePair bnv : ((List<BasicNameValuePair>) parameters)) {
|
||||
sb.append(bnv.getValue()).append(separator);
|
||||
}
|
||||
}
|
||||
|
||||
return StringUtils.isBlank(sb.toString())?"":sb.deleteCharAt(sb.length() - 1).toString();
|
||||
return StringUtils.isBlank(sb.toString()) ? "" : sb.deleteCharAt(sb.length() - 1).toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取随机字符串
|
||||
*
|
||||
* @return 随机字符串
|
||||
*/
|
||||
public static String randomStr(){
|
||||
public static String randomStr() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
@@ -306,24 +339,26 @@ public enum SignUtils implements SignType {
|
||||
/**
|
||||
* 签名
|
||||
*
|
||||
* @param parameters 需要进行排序签名的参数
|
||||
* @param key 密钥
|
||||
* @param parameters 需要进行排序签名的参数
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public String sign(Map parameters, String key, String characterEncoding) {
|
||||
public String sign(Map parameters, String key, String characterEncoding) {
|
||||
|
||||
return createSign(parameterText(parameters, "&"), key, characterEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名
|
||||
* @param parameters 需要进行排序签名的参数
|
||||
* @param key 密钥
|
||||
* @param separator 分隔符 默认 &
|
||||
*
|
||||
* @param parameters 需要进行排序签名的参数
|
||||
* @param key 密钥
|
||||
* @param separator 分隔符 默认 &
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public String sign(Map parameters, String key, String separator, String characterEncoding) {
|
||||
public String sign(Map parameters, String key, String separator, String characterEncoding) {
|
||||
|
||||
return createSign(parameterText(parameters, separator), key, characterEncoding);
|
||||
|
||||
@@ -333,17 +368,16 @@ public enum SignUtils implements SignType {
|
||||
/**
|
||||
* 签名字符串
|
||||
*
|
||||
* @param params 需要签名的字符串
|
||||
* @param params 需要签名的字符串
|
||||
* @param sign 签名结果
|
||||
* @param key 密钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名结果
|
||||
*/
|
||||
public boolean verify(Map params, String sign, String key, String characterEncoding){
|
||||
public boolean verify(Map params, String sign, String key, String characterEncoding) {
|
||||
//判断是否一样
|
||||
return this.verify(parameterText(params), sign, key, characterEncoding);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
|
||||
package com.egzosn.pay.common.util.sign.encrypt;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.*;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
@@ -10,288 +15,324 @@ import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* RSA
|
||||
*
|
||||
* @author egan
|
||||
* <pre>
|
||||
* email egzosn@gmail.com
|
||||
*</pre>
|
||||
* </pre>
|
||||
*/
|
||||
public class RSA{
|
||||
|
||||
private static final String ALGORITHM = "RSA";
|
||||
public class RSA {
|
||||
private static final Log LOG = LogFactory.getLog(RSA.class);
|
||||
private static final String ALGORITHM = "RSA";
|
||||
|
||||
|
||||
private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
|
||||
private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
|
||||
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, String privateKey, String signAlgorithms, String characterEncoding) {
|
||||
try {
|
||||
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
|
||||
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
|
||||
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
|
||||
/**
|
||||
* RSA签名
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, String privateKey, String signAlgorithms, String characterEncoding) {
|
||||
try {
|
||||
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
|
||||
KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
|
||||
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
|
||||
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
|
||||
signature.initSign(priKey);
|
||||
signature.update(content.getBytes(characterEncoding));
|
||||
signature.initSign(priKey);
|
||||
signature.update(content.getBytes(characterEncoding));
|
||||
|
||||
byte[] signed = signature.sign();
|
||||
byte[] signed = signature.sign();
|
||||
|
||||
return Base64.encode(signed);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return Base64.encode(signed);
|
||||
}
|
||||
catch (GeneralSecurityException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, PrivateKey privateKey, String signAlgorithms, String characterEncoding) {
|
||||
try {
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
signature.initSign(privateKey);
|
||||
signature.update(content.getBytes(characterEncoding));
|
||||
byte[] signed = signature.sign();
|
||||
return Base64.encode(signed);
|
||||
}
|
||||
catch (GeneralSecurityException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, PrivateKey privateKey, String signAlgorithms, String characterEncoding) {
|
||||
try {
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
signature.initSign(privateKey);
|
||||
signature.update(content.getBytes(characterEncoding));
|
||||
byte[] signed = signature.sign();
|
||||
return Base64.encode(signed);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, String privateKey ,String characterEncoding){
|
||||
/**
|
||||
* RSA签名
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, String privateKey, String characterEncoding) {
|
||||
return sign(content, privateKey, SIGN_ALGORITHMS, characterEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA签名
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, PrivateKey privateKey ,String characterEncoding){
|
||||
/**
|
||||
* RSA签名
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 签名值
|
||||
*/
|
||||
public static String sign(String content, PrivateKey privateKey, String characterEncoding) {
|
||||
return sign(content, privateKey, SIGN_ALGORITHMS, characterEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA验签名检查
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, String publicKey, String signAlgorithms, String characterEncoding){
|
||||
try {
|
||||
PublicKey pubKey = getPublicKey(publicKey, ALGORITHM);
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
signature.initVerify(pubKey);
|
||||
signature.update(content.getBytes(characterEncoding) );
|
||||
return signature.verify(Base64.decode(sign) );
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* RSA验签名检查
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, String publicKey, String signAlgorithms, String characterEncoding) {
|
||||
try {
|
||||
PublicKey pubKey = getPublicKey(publicKey, ALGORITHM);
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
signature.initVerify(pubKey);
|
||||
signature.update(content.getBytes(characterEncoding));
|
||||
return signature.verify(Base64.decode(sign));
|
||||
}
|
||||
catch (GeneralSecurityException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA验签名检查
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, PublicKey publicKey, String signAlgorithms, String characterEncoding){
|
||||
try {
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
signature.initVerify(publicKey);
|
||||
signature.update(content.getBytes(characterEncoding) );
|
||||
return signature.verify(Base64.decode(sign) );
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* RSA验签名检查
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, String publicKey, String characterEncoding){
|
||||
/**
|
||||
* RSA验签名检查
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param signAlgorithms 签名算法
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, PublicKey publicKey, String signAlgorithms, String characterEncoding) {
|
||||
try {
|
||||
java.security.Signature signature = java.security.Signature.getInstance(signAlgorithms);
|
||||
signature.initVerify(publicKey);
|
||||
signature.update(content.getBytes(characterEncoding));
|
||||
return signature.verify(Base64.decode(sign));
|
||||
}
|
||||
catch (GeneralSecurityException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return verify(content, sign, publicKey, SIGN_ALGORITHMS, characterEncoding);
|
||||
}
|
||||
/**
|
||||
* RSA验签名检查
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, String publicKey, String characterEncoding) {
|
||||
|
||||
return verify(content, sign, publicKey, SIGN_ALGORITHMS, characterEncoding);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* RSA验签名检查
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, PublicKey publicKey, String characterEncoding){
|
||||
return verify(content, sign, publicKey, SIGN_ALGORITHMS, characterEncoding);
|
||||
}
|
||||
/**
|
||||
* RSA验签名检查
|
||||
*
|
||||
* @param content 待签名数据
|
||||
* @param sign 签名值
|
||||
* @param publicKey 公钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 布尔值
|
||||
*/
|
||||
public static boolean verify(String content, String sign, PublicKey publicKey, String characterEncoding) {
|
||||
return verify(content, sign, publicKey, SIGN_ALGORITHMS, characterEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
* @param content 密文
|
||||
* @param privateKey 商户私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 解密后的字符串
|
||||
* @throws GeneralSecurityException 解密异常
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static String decrypt(String content, String privateKey, String characterEncoding) throws GeneralSecurityException, IOException {
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param content 密文
|
||||
* @param privateKey 商户私钥
|
||||
* @param characterEncoding 编码格式
|
||||
* @return 解密后的字符串
|
||||
* @throws GeneralSecurityException 解密异常
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static String decrypt(String content, String privateKey, String characterEncoding) throws GeneralSecurityException, IOException {
|
||||
PrivateKey prikey = getPrivateKey(privateKey);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.DECRYPT_MODE, prikey);
|
||||
try(InputStream ins = new ByteArrayInputStream(Base64.decode(content)); ByteArrayOutputStream writer = new ByteArrayOutputStream();) {
|
||||
try (InputStream ins = new ByteArrayInputStream(Base64.decode(content)); ByteArrayOutputStream writer = new ByteArrayOutputStream();) {
|
||||
|
||||
//rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
|
||||
byte[] buf = new byte[128];
|
||||
int bufl;
|
||||
while ((bufl = ins.read(buf)) != -1) {
|
||||
byte[] block = null;
|
||||
//rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
|
||||
byte[] buf = new byte[128];
|
||||
int bufl;
|
||||
while ((bufl = ins.read(buf)) != -1) {
|
||||
byte[] block = null;
|
||||
|
||||
if (buf.length == bufl) {
|
||||
block = buf;
|
||||
} else {
|
||||
block = new byte[bufl];
|
||||
if (buf.length == bufl) {
|
||||
block = buf;
|
||||
}
|
||||
else {
|
||||
block = new byte[bufl];
|
||||
|
||||
for (int i = 0; i < bufl; i++) {
|
||||
block[i] = buf[i];
|
||||
}
|
||||
}
|
||||
writer.write(cipher.doFinal(block));
|
||||
}
|
||||
for (int i = 0; i < bufl; i++) {
|
||||
block[i] = buf[i];
|
||||
}
|
||||
}
|
||||
writer.write(cipher.doFinal(block));
|
||||
}
|
||||
|
||||
return new String(writer.toByteArray(), characterEncoding);
|
||||
}
|
||||
return new String(writer.toByteArray(), characterEncoding);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 得到私钥
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @throws GeneralSecurityException 加密异常
|
||||
* @return 私钥
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(String key) throws GeneralSecurityException {
|
||||
/**
|
||||
* 得到私钥
|
||||
*
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @return 私钥
|
||||
* @throws GeneralSecurityException 加密异常
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(String key) throws GeneralSecurityException {
|
||||
|
||||
byte[] keyBytes;
|
||||
keyBytes = Base64.decode(key);
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
|
||||
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
|
||||
return privateKey;
|
||||
}
|
||||
byte[] keyBytes;
|
||||
keyBytes = Base64.decode(key);
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
|
||||
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到公钥
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @param signAlgorithms 密钥类型
|
||||
* @throws GeneralSecurityException 加密异常
|
||||
* @throws IOException 加密异常
|
||||
* @return 公钥
|
||||
*/
|
||||
public static PublicKey getPublicKey(String key, String signAlgorithms) throws GeneralSecurityException, IOException {
|
||||
try (ByteArrayInputStream is = new ByteArrayInputStream(key.getBytes("ISO8859-1"))){
|
||||
return getPublicKey(is, signAlgorithms);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 得到公钥
|
||||
*
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @param signAlgorithms 密钥类型
|
||||
* @return 公钥
|
||||
* @throws GeneralSecurityException 加密异常
|
||||
* @throws IOException 加密异常
|
||||
*/
|
||||
public static PublicKey getPublicKey(String key, String signAlgorithms) throws GeneralSecurityException, IOException {
|
||||
try (ByteArrayInputStream is = new ByteArrayInputStream(key.getBytes("ISO8859-1"))) {
|
||||
return getPublicKey(is, signAlgorithms);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 得到公钥
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @throws GeneralSecurityException 加密异常
|
||||
* @throws IOException 加密异常
|
||||
* @return 公钥
|
||||
*/
|
||||
public static PublicKey getPublicKey(String key) throws GeneralSecurityException, IOException {
|
||||
/**
|
||||
* 得到公钥
|
||||
*
|
||||
* @param key 密钥字符串(经过base64编码)
|
||||
* @return 公钥
|
||||
* @throws GeneralSecurityException 加密异常
|
||||
* @throws IOException 加密异常
|
||||
*/
|
||||
public static PublicKey getPublicKey(String key) throws GeneralSecurityException, IOException {
|
||||
|
||||
return getPublicKey(key, ALGORITHM);
|
||||
}
|
||||
return getPublicKey(key, ALGORITHM);
|
||||
}
|
||||
|
||||
public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws IOException, GeneralSecurityException {
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String readLine = null;
|
||||
while ((readLine = br.readLine()) != null) {
|
||||
if (readLine.charAt(0) == '-') {
|
||||
continue;
|
||||
}
|
||||
sb.append(readLine);
|
||||
sb.append('\r');
|
||||
}
|
||||
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(sb.toString()));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
|
||||
PublicKey publicKey = keyFactory.generatePublic(pubX509);
|
||||
return publicKey;
|
||||
}
|
||||
}
|
||||
public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws IOException, GeneralSecurityException {
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String readLine = null;
|
||||
while ((readLine = br.readLine()) != null) {
|
||||
if (readLine.charAt(0) == '-') {
|
||||
continue;
|
||||
}
|
||||
sb.append(readLine);
|
||||
sb.append('\r');
|
||||
}
|
||||
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(sb.toString()));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
|
||||
PublicKey publicKey = keyFactory.generatePublic(pubX509);
|
||||
return publicKey;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] encrypt(byte[] plainBytes, PublicKey publicKey, int keyLength, int reserveSize, String cipherAlgorithm) throws IOException, GeneralSecurityException {
|
||||
int keyByteSize = keyLength / 8;
|
||||
int encryptBlockSize = keyByteSize - reserveSize;
|
||||
int nBlock = plainBytes.length / encryptBlockSize;
|
||||
if ((plainBytes.length % encryptBlockSize) != 0) {
|
||||
nBlock += 1;
|
||||
}
|
||||
try (ByteArrayOutputStream outbuf = new ByteArrayOutputStream(nBlock * keyByteSize)) {
|
||||
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
for (int offset = 0; offset < plainBytes.length; offset += encryptBlockSize) {
|
||||
int inputLen = plainBytes.length - offset;
|
||||
if (inputLen > encryptBlockSize) {
|
||||
inputLen = encryptBlockSize;
|
||||
}
|
||||
byte[] encryptedBlock = cipher.doFinal(plainBytes, offset, inputLen);
|
||||
outbuf.write(encryptedBlock);
|
||||
}
|
||||
outbuf.flush();
|
||||
return outbuf.toByteArray();
|
||||
}
|
||||
}
|
||||
public static String encrypt(String content, String publicKey, String cipherAlgorithm, String characterEncoding ) throws IOException, GeneralSecurityException {
|
||||
return Base64.encode(RSA.encrypt(content.getBytes(characterEncoding), RSA.getPublicKey(publicKey),1024, 11, cipherAlgorithm));
|
||||
}
|
||||
public static byte[] encrypt(byte[] plainBytes, PublicKey publicKey, int keyLength, int reserveSize, String cipherAlgorithm) throws IOException, GeneralSecurityException {
|
||||
int keyByteSize = keyLength / 8;
|
||||
int encryptBlockSize = keyByteSize - reserveSize;
|
||||
int nBlock = plainBytes.length / encryptBlockSize;
|
||||
if ((plainBytes.length % encryptBlockSize) != 0) {
|
||||
nBlock += 1;
|
||||
}
|
||||
try (ByteArrayOutputStream outbuf = new ByteArrayOutputStream(nBlock * keyByteSize)) {
|
||||
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
for (int offset = 0; offset < plainBytes.length; offset += encryptBlockSize) {
|
||||
int inputLen = plainBytes.length - offset;
|
||||
if (inputLen > encryptBlockSize) {
|
||||
inputLen = encryptBlockSize;
|
||||
}
|
||||
byte[] encryptedBlock = cipher.doFinal(plainBytes, offset, inputLen);
|
||||
outbuf.write(encryptedBlock);
|
||||
}
|
||||
outbuf.flush();
|
||||
return outbuf.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static String encrypt(String content, String publicKey, String cipherAlgorithm, String characterEncoding) throws IOException, GeneralSecurityException {
|
||||
return Base64.encode(RSA.encrypt(content.getBytes(characterEncoding), RSA.getPublicKey(publicKey), 1024, 11, cipherAlgorithm));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -137,7 +137,8 @@ public class SM3 {
|
||||
private static int FFj(int X, int Y, int Z, int j) {
|
||||
if (j >= 0 && j <= 15) {
|
||||
return FF1j(X, Y, Z);
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
return FF2j(X, Y, Z);
|
||||
}
|
||||
}
|
||||
@@ -145,7 +146,8 @@ public class SM3 {
|
||||
private static int GGj(int X, int Y, int Z, int j) {
|
||||
if (j >= 0 && j <= 15) {
|
||||
return GG1j(X, Y, Z);
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
return GG2j(X, Y, Z);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,34 @@
|
||||
package com.egzosn.pay.common.util.sign.encrypt.sm3;
|
||||
|
||||
public class SM3Digest {
|
||||
/** SM3值的长度 */
|
||||
/**
|
||||
* SM3值的长度
|
||||
*/
|
||||
private static final int BYTE_LENGTH = 32;
|
||||
|
||||
/** SM3分组长度 */
|
||||
/**
|
||||
* SM3分组长度
|
||||
*/
|
||||
private static final int BLOCK_LENGTH = 64;
|
||||
|
||||
/** 缓冲区长度 */
|
||||
/**
|
||||
* 缓冲区长度
|
||||
*/
|
||||
private static final int BUFFER_LENGTH = BLOCK_LENGTH * 1;
|
||||
|
||||
/** 缓冲区 */
|
||||
/**
|
||||
* 缓冲区
|
||||
*/
|
||||
private byte[] xBuf = new byte[BUFFER_LENGTH];
|
||||
|
||||
/** 缓冲区偏移量 */
|
||||
/**
|
||||
* 缓冲区偏移量
|
||||
*/
|
||||
private int xBufOff;
|
||||
|
||||
/** 初始向量 */
|
||||
/**
|
||||
* 初始向量
|
||||
*/
|
||||
private byte[] V = SM3.iv.clone();
|
||||
|
||||
private int cntBlock = 0;
|
||||
@@ -25,7 +37,7 @@ public class SM3Digest {
|
||||
}
|
||||
|
||||
|
||||
public SM3Digest(SM3Digest t){
|
||||
public SM3Digest(SM3Digest t) {
|
||||
System.arraycopy(t.xBuf, 0, this.xBuf, 0, t.xBuf.length);
|
||||
this.xBufOff = t.xBufOff;
|
||||
System.arraycopy(t.V, 0, this.V, 0, t.V.length);
|
||||
@@ -34,12 +46,11 @@ public class SM3Digest {
|
||||
/**
|
||||
* SM3结果输出
|
||||
*
|
||||
* @param out 保存SM3结构的缓冲区
|
||||
* @param out 保存SM3结构的缓冲区
|
||||
* @param outOff 缓冲区偏移量
|
||||
* @return 字节长度
|
||||
*/
|
||||
public int doFinal(byte[] out, int outOff)
|
||||
{
|
||||
public int doFinal(byte[] out, int outOff) {
|
||||
byte[] tmp = doFinal();
|
||||
System.arraycopy(tmp, 0, out, 0, tmp.length);
|
||||
return BYTE_LENGTH;
|
||||
@@ -48,8 +59,7 @@ public class SM3Digest {
|
||||
/**
|
||||
* 重置
|
||||
*/
|
||||
public void reset()
|
||||
{
|
||||
public void reset() {
|
||||
xBufOff = 0;
|
||||
cntBlock = 0;
|
||||
V = SM3.iv.clone();
|
||||
@@ -58,23 +68,20 @@ public class SM3Digest {
|
||||
/**
|
||||
* 明文输入
|
||||
*
|
||||
* @param in 明文输入缓冲区
|
||||
* @param in 明文输入缓冲区
|
||||
* @param inOff 缓冲区偏移量
|
||||
* @param len 明文长度
|
||||
* @param len 明文长度
|
||||
*/
|
||||
public void update(byte[] in, int inOff, int len)
|
||||
{
|
||||
public void update(byte[] in, int inOff, int len) {
|
||||
int partLen = BUFFER_LENGTH - xBufOff;
|
||||
int inputLen = len;
|
||||
int dPos = inOff;
|
||||
if (partLen < inputLen)
|
||||
{
|
||||
if (partLen < inputLen) {
|
||||
System.arraycopy(in, dPos, xBuf, xBufOff, partLen);
|
||||
inputLen -= partLen;
|
||||
dPos += partLen;
|
||||
doUpdate();
|
||||
while (inputLen > BUFFER_LENGTH)
|
||||
{
|
||||
while (inputLen > BUFFER_LENGTH) {
|
||||
System.arraycopy(in, dPos, xBuf, 0, BUFFER_LENGTH);
|
||||
inputLen -= BUFFER_LENGTH;
|
||||
dPos += BUFFER_LENGTH;
|
||||
@@ -89,11 +96,9 @@ public class SM3Digest {
|
||||
/**
|
||||
* 更新
|
||||
*/
|
||||
private void doUpdate()
|
||||
{
|
||||
private void doUpdate() {
|
||||
byte[] B = new byte[BLOCK_LENGTH];
|
||||
for (int i = 0; i < BUFFER_LENGTH; i += BLOCK_LENGTH)
|
||||
{
|
||||
for (int i = 0; i < BUFFER_LENGTH; i += BLOCK_LENGTH) {
|
||||
System.arraycopy(xBuf, i, B, 0, B.length);
|
||||
doHash(B);
|
||||
}
|
||||
@@ -102,37 +107,33 @@ public class SM3Digest {
|
||||
|
||||
/**
|
||||
* 转16进制
|
||||
*
|
||||
* @param B 字节数组
|
||||
*/
|
||||
private void doHash(byte[] B)
|
||||
{
|
||||
private void doHash(byte[] B) {
|
||||
byte[] tmp = SM3.CF(V, B);
|
||||
System.arraycopy(tmp, 0, V, 0, V.length);
|
||||
cntBlock++;
|
||||
}
|
||||
|
||||
private byte[] doFinal()
|
||||
{
|
||||
private byte[] doFinal() {
|
||||
byte[] B = new byte[BLOCK_LENGTH];
|
||||
byte[] buffer = new byte[xBufOff];
|
||||
System.arraycopy(xBuf, 0, buffer, 0, buffer.length);
|
||||
byte[] tmp = SM3.padding(buffer, cntBlock);
|
||||
for (int i = 0; i < tmp.length; i += BLOCK_LENGTH)
|
||||
{
|
||||
for (int i = 0; i < tmp.length; i += BLOCK_LENGTH) {
|
||||
System.arraycopy(tmp, i, B, 0, B.length);
|
||||
doHash(B);
|
||||
}
|
||||
return V;
|
||||
}
|
||||
|
||||
public void update(byte in)
|
||||
{
|
||||
byte[] buffer = new byte[] { in };
|
||||
public void update(byte in) {
|
||||
byte[] buffer = new byte[]{in};
|
||||
update(buffer, 0, 1);
|
||||
}
|
||||
|
||||
public int getDigestSize()
|
||||
{
|
||||
public int getDigestSize() {
|
||||
return BYTE_LENGTH;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user