Main.java
public class Main {
public static void main(String[] args) {
String pfxpwd = "217526";// 私钥密码
String pfxpath = "D:\\CER\\8000013189_pri.pfx";//商户私钥路径
String base64str = "123456";// 待加密的字符串
base64str.replaceAll("\r", "").replaceAll("\n", "");//重要 避免出现换行空格符
String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfxpwd);//加密数据
System.out.println(data_content);
}
}
RsaCodingUtil.java
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
* <b>Rsa加解密工具</b><br>
* <br>
* 公钥采用X509,Cer格式的<br>
* 私钥采用PKCS12加密方式的PFX私钥文件<br>
* 加密算法为1024位的RSA,填充算法为PKCS1Padding<br>
*
* @author 行者
* @version 4.1.0
*/
public final class RsaCodingUtil {
// ======================================================================================
// 公钥加密私钥解密段
// ======================================================================================
/**
* 指定Cer公钥路径加密
*
* @param src
* @param pubCerPath
* @return hex串
*/
public static String encryptByPubCerFile(String src, String pubCerPath) {
PublicKey publicKey = RsaReadUtil.getPublicKeyFromFile(pubCerPath);
if (publicKey == null) {
return null;
}
return encryptByPublicKey(src, publicKey);
}
/**
* 用公钥内容加密
*
* @param src
* @param pubKeyText
* @return hex串
*/
public static String encryptByPubCerText(String src, String pubKeyText) {
PublicKey publicKey = RsaReadUtil.getPublicKeyByText(pubKeyText);
if (publicKey == null) {
return null;
}
return encryptByPublicKey(src, publicKey);
}
/**
* 公钥加密返回
*
* @param src
* @param publicKey
* @param encryptMode
* @return hex串
*/
public static String encryptByPublicKey(String src, PublicKey publicKey) {
byte[] destBytes = rsaByPublicKey(src.getBytes(), publicKey, Cipher.ENCRYPT_MODE);
if (destBytes == null) {
return null;
}
return FormatUtil.byte2Hex(destBytes);
}
/**
* 根据私钥文件解密
*
* @param src
* @param pfxPath
* @param priKeyPass
* @return
*/
public static String decryptByPriPfxFile(String src, String pfxPath, String priKeyPass) {
if (FormatUtil.isEmpty(src) || FormatUtil.isEmpty(pfxPath)) {
return null;
}
PrivateKey privateKey = RsaReadUtil.getPrivateKeyFromFile(pfxPath, priKeyPass);
if (privateKey == null) {
return null;
}
return decryptByPrivateKey(src, privateKey);
}
/**
* 根据私钥文件流解密
*
* @param src
* @param pfxPath
* @param priKeyPass
* @return
*/
public static String decryptByPriPfxStream(String src, byte[] pfxBytes, String priKeyPass) {
if (FormatUtil.isEmpty(src)) {
return null;
}
PrivateKey privateKey = RsaReadUtil.getPrivateKeyByStream(pfxBytes, priKeyPass);
if (privateKey == null) {
return null;
}
return decryptByPrivateKey(src, privateKey);
}
/**
* 私钥解密
*
* @param src
* @param privateKey
* @return
*/
public static String decryptByPrivateKey(String src, PrivateKey privateKey) {
if (FormatUtil.isEmpty(src)) {
return null;
}
try {
byte[] destBytes = rsaByPrivateKey(FormatUtil.hex2Bytes(src), privateKey, Cipher.DECRYPT_MODE);
if (destBytes == null) {
return null;
}
return new String(destBytes, RsaConst.ENCODE);
} catch (UnsupportedEncodingException e) {
// //log.error("解密内容不是正确的UTF8格式:", e);
} catch (Exception e) {
// //log.error("解密内容异常", e);
}
return null;
}
// ======================================================================================
// 私钥加密公钥解密
// ======================================================================================
/**
* 根据私钥文件加密
*
* @param src
* @param pfxPath
* @param priKeyPass
* @return
*/
public static String encryptByPriPfxFile(String src, String pfxPath, String priKeyPass) {
PrivateKey privateKey = RsaReadUtil.getPrivateKeyFromFile(pfxPath, priKeyPass);
if (privateKey == null) {
return null;
}
return encryptByPrivateKey(src, privateKey);
}
/**
* 根据私钥文件流加密
*
* @param src
* @param pfxPath
* @param priKeyPass
* @return
*/
public static String encryptByPriPfxStream(String src, byte[] pfxBytes, String priKeyPass) {
PrivateKey privateKey = RsaReadUtil.getPrivateKeyByStream(pfxBytes, priKeyPass);
if (privateKey == null) {
return null;
}
return encryptByPrivateKey(src, privateKey);
}
/**
* 根据私钥加密
*
* @param src
* @param privateKey
*/
public static String encryptByPrivateKey(String src, PrivateKey privateKey) {
byte[] destBytes = rsaByPrivateKey(src.getBytes(), privateKey, Cipher.ENCRYPT_MODE);
if (destBytes == null) {
return null;
}
return FormatUtil.byte2Hex(destBytes);
}
/**
* 指定Cer公钥路径解密
*
* @param src
* @param pubCerPath
* @return
*/
public static String decryptByPubCerFile(String src, String pubCerPath) {
PublicKey publicKey = RsaReadUtil.getPublicKeyFromFile(pubCerPath);
if (publicKey == null) {
return null;
}
return decryptByPublicKey(src, publicKey);
}
/**
* 根据公钥文本解密
*
* @param src
* @param pubKeyText
* @return
*/
public static String decryptByPubCerText(String src, String pubKeyText) {
PublicKey publicKey = RsaReadUtil.getPublicKeyByText(pubKeyText);
if (publicKey == null) {
return null;
}
return decryptByPublicKey(src, publicKey);
}
/**
* 根据公钥解密
*
* @param src
* @param publicKey
* @return
*/
public static String decryptByPublicKey(String src, PublicKey publicKey) {
try {
byte[] destBytes = rsaByPublicKey(FormatUtil.hex2Bytes(src), publicKey, Cipher.DECRYPT_MODE);
if (destBytes == null) {
return null;
}
return new String(destBytes, RsaConst.ENCODE);
} catch (UnsupportedEncodingException e) {
log("解密出错" + e);
}
return null;
}
// ======================================================================================
// 公私钥算法
// ======================================================================================
/**
* 公钥算法
*
* @param srcData 源字节
* @param publicKey 公钥
* @param mode 加密 OR 解密
* @return
*/
public static byte[] rsaByPublicKey(byte[] srcData, PublicKey publicKey, int mode) {
try {
Cipher cipher = Cipher.getInstance(RsaConst.RSA_CHIPER);
cipher.init(mode, publicKey);
// 分段加密
int blockSize = (mode == Cipher.ENCRYPT_MODE) ? RsaConst.ENCRYPT_KEYSIZE : RsaConst.DECRYPT_KEYSIZE;
byte[] encryptedData = null;
for (int i = 0; i < srcData.length; i += blockSize) {
// 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
byte[] doFinal = cipher.doFinal(subarray(srcData, i, i + blockSize));
encryptedData = addAll(encryptedData, doFinal);
}
return encryptedData;
} catch (NoSuchAlgorithmException e) {
// //log.error("公钥算法-不存在的解密算法:", e);
} catch (NoSuchPaddingException e) {
// //log.error("公钥算法-无效的补位算法:", e);
} catch (IllegalBlockSizeException e) {
// //log.error("公钥算法-无效的块大小:", e);
} catch (BadPaddingException e) {
// //log.error("公钥算法-补位算法异常:", e);
} catch (InvalidKeyException e) {
// //log.error("公钥算法-无效的私钥:", e);
}
return null;
}
/**
* 私钥算法
*
* @param srcData 源字节
* @param privateKey 私钥
* @param mode 加密 OR 解密
* @return
*/
public static byte[] rsaByPrivateKey(byte[] srcData, PrivateKey privateKey, int mode) {
try {
Cipher cipher = Cipher.getInstance(RsaConst.RSA_CHIPER);
cipher.init(mode, privateKey);
// 分段加密
int blockSize = (mode == Cipher.ENCRYPT_MODE) ? RsaConst.ENCRYPT_KEYSIZE : RsaConst.DECRYPT_KEYSIZE;
byte[] decryptData = null;
for (int i = 0; i < srcData.length; i += blockSize) {
byte[] doFinal = cipher.doFinal(subarray(srcData, i, i + blockSize));
decryptData = addAll(decryptData, doFinal);
}
return decryptData;
} catch (NoSuchAlgorithmException e) {
// //log.error("私钥算法-不存在的解密算法:", e);
} catch (NoSuchPaddingException e) {
// log.error("私钥算法-无效的补位算法:", e);
} catch (IllegalBlockSizeException e) {
// log.error("私钥算法-无效的块大小:", e);
} catch (BadPaddingException e) {
// log.error("私钥算法-补位算法异常:", e);
} catch (InvalidKeyException e) {
// log.error("私钥算法-无效的私钥:", e);
}
return null;
}
// /////////////==========================
public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new byte[0];
}
byte[] subarray = new byte[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
public static byte[] addAll(byte[] array1, byte[] array2) {
if (array1 == null) {
return clone(array2);
} else if (array2 == null) {
return clone(array1);
}
byte[] joinedArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
public static byte[] clone(byte[] array) {
if (array == null) {
return null;
}
return (byte[]) array.clone();
}
public static void log(String msg) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg);
}
}
RsaReadUtil.java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Enumeration;
import sun.misc.BASE64Decoder;
//import com.jweb.//log.Logger;
/**
* <b>公私钥读取工具</b><br>
* <br>
*
* @author 行者
* @version 4.1.0
*/
public final class RsaReadUtil {
/**
* 根据Cer文件读取公钥
*
* @param pubCerPath
* @return
*/
public static PublicKey getPublicKeyFromFile(String pubCerPath) {
FileInputStream pubKeyStream = null;
try {
pubKeyStream = new FileInputStream(pubCerPath);
byte[] reads = new byte[pubKeyStream.available()];
pubKeyStream.read(reads);
return getPublicKeyByText(new String(reads));
} catch (FileNotFoundException e) {
// //log.error("公钥文件不存在:", e);
} catch (IOException e) {
// log.error("公钥文件读取失败:", e);
} finally {
if (pubKeyStream != null) {
try {
pubKeyStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 根据公钥Cer文本串读取公钥
*
* @param pubKeyText
* @return
*/
public static PublicKey getPublicKeyByText(String pubKeyText) {
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance(RsaConst.KEY_X509);
BufferedReader br = new BufferedReader(new StringReader(pubKeyText));
String line = null;
StringBuilder keyBuffer = new StringBuilder();
while ((line = br.readLine()) != null) {
if (!line.startsWith("-")) {
keyBuffer.append(line);
}
}
Certificate certificate = certificateFactory.generateCertificate(
new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(keyBuffer.toString())));
return certificate.getPublicKey();
} catch (Exception e) {
// log.error("解析公钥内容失败:", e);
}
return null;
}
/**
* 根据私钥路径读取私钥
*
* @param pfxPath
* @param priKeyPass
* @return
*/
public static PrivateKey getPrivateKeyFromFile(String pfxPath, String priKeyPass) {
InputStream priKeyStream = null;
try {
priKeyStream = new FileInputStream(pfxPath);
byte[] reads = new byte[priKeyStream.available()];
priKeyStream.read(reads);
return getPrivateKeyByStream(reads, priKeyPass);
} catch (Exception e) {
// log.error("解析文件,读取私钥失败:", e);
} finally {
if (priKeyStream != null) {
try {
priKeyStream.close();
} catch (Exception e) {
//
}
}
}
return null;
}
/**
* 根据PFX私钥字节流读取私钥
*
* @param pfxBytes
* @param priKeyPass
* @return
*/
public static PrivateKey getPrivateKeyByStream(byte[] pfxBytes, String priKeyPass) {
try {
KeyStore ks = KeyStore.getInstance(RsaConst.KEY_PKCS12);
char[] charPriKeyPass = priKeyPass.toCharArray();
ks.load(new ByteArrayInputStream(pfxBytes), charPriKeyPass);
Enumeration<String> aliasEnum = ks.aliases();
String keyAlias = null;
if (aliasEnum.hasMoreElements()) {
keyAlias = (String) aliasEnum.nextElement();
}
return (PrivateKey) ks.getKey(keyAlias, charPriKeyPass);
} catch (IOException e) {
// 加密失败
// log.error("解析文件,读取私钥失败:", e);
} catch (KeyStoreException e) {
// log.error("私钥存储异常:", e);
} catch (NoSuchAlgorithmException e) {
// log.error("不存在的解密算法:", e);
} catch (CertificateException e) {
// log.error("证书异常:", e);
} catch (UnrecoverableKeyException e) {
// log.error("不可恢复的秘钥异常", e);
}
return null;
}
}
RsaConst.java
public final class RsaConst {
/** 编码 */
public final static String ENCODE = "UTF-8";
public final static String KEY_X509 = "X509";
public final static String KEY_PKCS12 = "PKCS12";
public final static String KEY_ALGORITHM = "RSA";
public final static String CER_ALGORITHM = "MD5WithRSA";
public final static String RSA_CHIPER = "RSA/ECB/PKCS1Padding";
public final static int KEY_SIZE = 1024;
/** 1024bit 加密块 大小 */
public final static int ENCRYPT_KEYSIZE = 117;
/** 1024bit 解密块 大小 */
public final static int DECRYPT_KEYSIZE = 128;
}
FormatUtil.java
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public final class FormatUtil {
/** ==============IS Base=================== */
/** 判断是否为整数(包括负数) */
public static boolean isNumber(Object arg) {
return NumberBo(0, toString(arg));
}
/** 判断是否为小数(包括整数,包括负数) */
public static boolean isDecimal(Object arg) {
return NumberBo(1, toString(arg));
}
/** 判断是否为空 ,为空返回true */
public static boolean isEmpty(Object arg) {
return toStringTrim(arg).length() == 0 ? true : false;
}
/** ==============TO Base=================== */
/**
* Object 转换成 Int 转换失败 返回默认值 0 <br>
* 使用:toInt(值,默认值[选填])
*/
public static int toInt(Object... args) {
int def = 0;
if (args != null) {
String str = toStringTrim(args[0]);
// 判断小数情况。舍弃小数位
int stri = str.indexOf('.');
str = stri > 0 ? str.substring(0, stri) : str;
if (args.length > 1)
def = Integer.parseInt(args[args.length - 1].toString());
if (isNumber(str))
return Integer.parseInt(str);
}
return def;
}
/**
* Object 转换成 Long 转换失败 返回默认值 0 <br>
* 使用:toLong(值,默认值[选填])
*/
public static long toLong(Object... args) {
Long def = 0L;
if (args != null) {
String str = toStringTrim(args[0]);
if (args.length > 1)
def = Long.parseLong(args[args.length - 1].toString());
if (isNumber(str))
return Long.parseLong(str);
}
return def;
}
/**
* Object 转换成 Double 转换失败 返回默认值 0 <br>
* 使用:toDouble(值,默认值[选填])
*/
public static double toDouble(Object... args) {
double def = 0;
if (args != null) {
String str = toStringTrim(args[0]);
if (args.length > 1)
def = Double.parseDouble(args[args.length - 1].toString());
if (isDecimal(str))
return Double.parseDouble(str);
}
return def;
}
/**
* Object 转换成 BigDecimal 转换失败 返回默认值 0 <br>
* 使用:toDecimal(值,默认值[选填]) 特别注意: new BigDecimal(Double) 会有误差,得先转String
*/
public static BigDecimal toDecimal(Object... args) {
return new BigDecimal(Double.toString(toDouble(args)));
}
/**
* Object 转换成 Boolean 转换失败 返回默认值 false <br>
* 使用:toBoolean(值,默认值[选填])
*/
public static boolean toBoolean(String bool) {
if (isEmpty(bool) || (!bool.equals("1") && !bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("ok")))
return false;
else
return true;
}
/**
* Object 转换成 String 为null 返回空字符 <br>
* 使用:toString(值,默认值[选填])
*/
public static String toString(Object... args) {
String def = "";
if (args != null) {
if (args.length > 1)
def = toString(args[args.length - 1]);
Object obj = args[0];
if (obj == null)
return def;
return obj.toString();
} else {
return def;
}
}
/**
* Object 转换成 String[去除所以空格]; 为null 返回空字符 <br>
* 使用:toStringTrim(值,默认值[选填])
*/
public static String toStringTrim(Object... args) {
String str = toString(args);
return str.replaceAll("\\s*", "");
}
/** ==============Other Base=================== */
public static String getNowTime() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
/** 数字左边补0 ,obj:要补0的数, length:补0后的长度 */
public static String leftPad(Object obj, int length) {
return String.format("%0" + length + "d", toInt(obj));
}
/** 小数 转 百分数 */
public static String toPercent(Double str) {
StringBuffer sb = new StringBuffer(Double.toString(str * 100.0000d));
return sb.append("%").toString();
}
/** 百分数 转 小数 */
public static Double toPercent2(String str) {
if (str.charAt(str.length() - 1) == '%')
return Double.parseDouble(str.substring(0, str.length() - 1)) / 100.0000d;
return 0d;
}
/**
* 将byte[] 转换成字符串
*/
public static String byte2Hex(byte[] srcBytes) {
StringBuilder hexRetSB = new StringBuilder();
for (byte b : srcBytes) {
String hexString = Integer.toHexString(0x00ff & b);
hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
}
return hexRetSB.toString();
}
/**
* 将16进制字符串转为转换成字符串
*/
public static byte[] hex2Bytes(String source) {
try {
byte[] sourceBytes = new byte[source.length() / 2];
for (int i = 0; i < sourceBytes.length; i++) {
sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
}
return sourceBytes;
} catch (NumberFormatException e) {
log("转换出错" + e);
throw new NumberFormatException();
}
}
/** String 转 Money */
public static String toMoney(Object str, String MoneyType) {
DecimalFormat df = new DecimalFormat(MoneyType);
if (isDecimal(str))
return df.format(toDecimal(str)).toString();
return df.format(toDecimal("0.00")).toString();
}
/** 获取字符串str 左边len位数 */
public static String getLeft(Object obj, int len) {
String str = toString(obj);
if (len <= 0)
return "";
if (str.length() <= len)
return str;
else
return str.substring(0, len);
}
/** 获取字符串str 右边len位数 */
public static String getRight(Object obj, int len) {
String str = toString(obj);
if (len <= 0)
return "";
if (str.length() <= len)
return str;
else
return str.substring(str.length() - len, str.length());
}
/**
* 首字母变小写
*/
public static String firstCharToLowerCase(String str) {
Character firstChar = str.charAt(0);
String tail = str.substring(1);
str = Character.toLowerCase(firstChar) + tail;
return str;
}
/**
* 首字母变大写
*/
public static String firstCharToUpperCase(String str) {
Character firstChar = str.charAt(0);
String tail = str.substring(1);
str = Character.toUpperCase(firstChar) + tail;
return str;
}
/**
* List集合去除重复值 只能用于基本数据类型,。 对象类集合,自己写
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List delMoreList(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
return newList;
}
public static String formatParams(String message, Object[] params) {
StringBuffer msg = new StringBuffer();
String temp = "";
for (int i = 0; i < params.length + 1; i++) {
int j = message.indexOf("{}") + 2;
if (j > 1) {
temp = message.substring(0, j);
temp = temp.replaceAll("\\{\\}", FormatUtil.toString(params[i]));
msg.append(temp);
message = message.substring(j);
} else {
msg.append(message);
message = "";
}
}
return msg.toString();
}
/** ============== END =================== */
public final static class MoneyType {
/** * 保留2位有效数字,整数位每3位逗号隔开 (默认) */
public static final String DECIMAL = "#,##0.00";
/** * 保留2位有效数字 */
public static final String DECIMAL_2 = "0.00";
/** * 保留4位有效数字 */
public static final String DECIMAL_4 = "0.0000";
}
private static boolean NumberBo(int type, Object obj) {
if (isEmpty(obj))
return false;
int points = 0;
int chr = 0;
String str = toString(obj);
for (int i = str.length(); --i >= 0;) {
chr = str.charAt(i);
if (chr < 48 || chr > 57) { // 判断数字
if (i == 0 && chr == 45) // 判断 - 号
return true;
if (i >= 0 && chr == 46 && type == 1) { // 判断 . 号
++points;
if (points <= 1)
continue;
}
return false;
}
}
return true;
}
public static void log(String msg) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg);
}
}
文档更新时间: 2019-06-17 14:44 作者:support