Main.java

  1. public class Main {
  2. public static void main(String[] args) {
  3. String pfxpwd = "217526";// 私钥密码
  4. String pfxpath = "D:\\CER\\8000013189_pri.pfx";//商户私钥路径
  5. String base64str = "123456";// 待加密的字符串
  6. base64str.replaceAll("\r", "").replaceAll("\n", "");//重要 避免出现换行空格符
  7. String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfxpwd);//加密数据
  8. System.out.println(data_content);
  9. }
  10. }

RsaCodingUtil.java

  1. import java.io.UnsupportedEncodingException;
  2. import java.security.InvalidKeyException;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.PrivateKey;
  5. import java.security.PublicKey;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import javax.crypto.BadPaddingException;
  9. import javax.crypto.Cipher;
  10. import javax.crypto.IllegalBlockSizeException;
  11. import javax.crypto.NoSuchPaddingException;
  12. /**
  13. * <b>Rsa加解密工具</b><br>
  14. * <br>
  15. * 公钥采用X509,Cer格式的<br>
  16. * 私钥采用PKCS12加密方式的PFX私钥文件<br>
  17. * 加密算法为1024位的RSA,填充算法为PKCS1Padding<br>
  18. *
  19. * @author 行者
  20. * @version 4.1.0
  21. */
  22. public final class RsaCodingUtil {
  23. // ======================================================================================
  24. // 公钥加密私钥解密段
  25. // ======================================================================================
  26. /**
  27. * 指定Cer公钥路径加密
  28. *
  29. * @param src
  30. * @param pubCerPath
  31. * @return hex串
  32. */
  33. public static String encryptByPubCerFile(String src, String pubCerPath) {
  34. PublicKey publicKey = RsaReadUtil.getPublicKeyFromFile(pubCerPath);
  35. if (publicKey == null) {
  36. return null;
  37. }
  38. return encryptByPublicKey(src, publicKey);
  39. }
  40. /**
  41. * 用公钥内容加密
  42. *
  43. * @param src
  44. * @param pubKeyText
  45. * @return hex串
  46. */
  47. public static String encryptByPubCerText(String src, String pubKeyText) {
  48. PublicKey publicKey = RsaReadUtil.getPublicKeyByText(pubKeyText);
  49. if (publicKey == null) {
  50. return null;
  51. }
  52. return encryptByPublicKey(src, publicKey);
  53. }
  54. /**
  55. * 公钥加密返回
  56. *
  57. * @param src
  58. * @param publicKey
  59. * @param encryptMode
  60. * @return hex串
  61. */
  62. public static String encryptByPublicKey(String src, PublicKey publicKey) {
  63. byte[] destBytes = rsaByPublicKey(src.getBytes(), publicKey, Cipher.ENCRYPT_MODE);
  64. if (destBytes == null) {
  65. return null;
  66. }
  67. return FormatUtil.byte2Hex(destBytes);
  68. }
  69. /**
  70. * 根据私钥文件解密
  71. *
  72. * @param src
  73. * @param pfxPath
  74. * @param priKeyPass
  75. * @return
  76. */
  77. public static String decryptByPriPfxFile(String src, String pfxPath, String priKeyPass) {
  78. if (FormatUtil.isEmpty(src) || FormatUtil.isEmpty(pfxPath)) {
  79. return null;
  80. }
  81. PrivateKey privateKey = RsaReadUtil.getPrivateKeyFromFile(pfxPath, priKeyPass);
  82. if (privateKey == null) {
  83. return null;
  84. }
  85. return decryptByPrivateKey(src, privateKey);
  86. }
  87. /**
  88. * 根据私钥文件流解密
  89. *
  90. * @param src
  91. * @param pfxPath
  92. * @param priKeyPass
  93. * @return
  94. */
  95. public static String decryptByPriPfxStream(String src, byte[] pfxBytes, String priKeyPass) {
  96. if (FormatUtil.isEmpty(src)) {
  97. return null;
  98. }
  99. PrivateKey privateKey = RsaReadUtil.getPrivateKeyByStream(pfxBytes, priKeyPass);
  100. if (privateKey == null) {
  101. return null;
  102. }
  103. return decryptByPrivateKey(src, privateKey);
  104. }
  105. /**
  106. * 私钥解密
  107. *
  108. * @param src
  109. * @param privateKey
  110. * @return
  111. */
  112. public static String decryptByPrivateKey(String src, PrivateKey privateKey) {
  113. if (FormatUtil.isEmpty(src)) {
  114. return null;
  115. }
  116. try {
  117. byte[] destBytes = rsaByPrivateKey(FormatUtil.hex2Bytes(src), privateKey, Cipher.DECRYPT_MODE);
  118. if (destBytes == null) {
  119. return null;
  120. }
  121. return new String(destBytes, RsaConst.ENCODE);
  122. } catch (UnsupportedEncodingException e) {
  123. // //log.error("解密内容不是正确的UTF8格式:", e);
  124. } catch (Exception e) {
  125. // //log.error("解密内容异常", e);
  126. }
  127. return null;
  128. }
  129. // ======================================================================================
  130. // 私钥加密公钥解密
  131. // ======================================================================================
  132. /**
  133. * 根据私钥文件加密
  134. *
  135. * @param src
  136. * @param pfxPath
  137. * @param priKeyPass
  138. * @return
  139. */
  140. public static String encryptByPriPfxFile(String src, String pfxPath, String priKeyPass) {
  141. PrivateKey privateKey = RsaReadUtil.getPrivateKeyFromFile(pfxPath, priKeyPass);
  142. if (privateKey == null) {
  143. return null;
  144. }
  145. return encryptByPrivateKey(src, privateKey);
  146. }
  147. /**
  148. * 根据私钥文件流加密
  149. *
  150. * @param src
  151. * @param pfxPath
  152. * @param priKeyPass
  153. * @return
  154. */
  155. public static String encryptByPriPfxStream(String src, byte[] pfxBytes, String priKeyPass) {
  156. PrivateKey privateKey = RsaReadUtil.getPrivateKeyByStream(pfxBytes, priKeyPass);
  157. if (privateKey == null) {
  158. return null;
  159. }
  160. return encryptByPrivateKey(src, privateKey);
  161. }
  162. /**
  163. * 根据私钥加密
  164. *
  165. * @param src
  166. * @param privateKey
  167. */
  168. public static String encryptByPrivateKey(String src, PrivateKey privateKey) {
  169. byte[] destBytes = rsaByPrivateKey(src.getBytes(), privateKey, Cipher.ENCRYPT_MODE);
  170. if (destBytes == null) {
  171. return null;
  172. }
  173. return FormatUtil.byte2Hex(destBytes);
  174. }
  175. /**
  176. * 指定Cer公钥路径解密
  177. *
  178. * @param src
  179. * @param pubCerPath
  180. * @return
  181. */
  182. public static String decryptByPubCerFile(String src, String pubCerPath) {
  183. PublicKey publicKey = RsaReadUtil.getPublicKeyFromFile(pubCerPath);
  184. if (publicKey == null) {
  185. return null;
  186. }
  187. return decryptByPublicKey(src, publicKey);
  188. }
  189. /**
  190. * 根据公钥文本解密
  191. *
  192. * @param src
  193. * @param pubKeyText
  194. * @return
  195. */
  196. public static String decryptByPubCerText(String src, String pubKeyText) {
  197. PublicKey publicKey = RsaReadUtil.getPublicKeyByText(pubKeyText);
  198. if (publicKey == null) {
  199. return null;
  200. }
  201. return decryptByPublicKey(src, publicKey);
  202. }
  203. /**
  204. * 根据公钥解密
  205. *
  206. * @param src
  207. * @param publicKey
  208. * @return
  209. */
  210. public static String decryptByPublicKey(String src, PublicKey publicKey) {
  211. try {
  212. byte[] destBytes = rsaByPublicKey(FormatUtil.hex2Bytes(src), publicKey, Cipher.DECRYPT_MODE);
  213. if (destBytes == null) {
  214. return null;
  215. }
  216. return new String(destBytes, RsaConst.ENCODE);
  217. } catch (UnsupportedEncodingException e) {
  218. log("解密出错" + e);
  219. }
  220. return null;
  221. }
  222. // ======================================================================================
  223. // 公私钥算法
  224. // ======================================================================================
  225. /**
  226. * 公钥算法
  227. *
  228. * @param srcData 源字节
  229. * @param publicKey 公钥
  230. * @param mode 加密 OR 解密
  231. * @return
  232. */
  233. public static byte[] rsaByPublicKey(byte[] srcData, PublicKey publicKey, int mode) {
  234. try {
  235. Cipher cipher = Cipher.getInstance(RsaConst.RSA_CHIPER);
  236. cipher.init(mode, publicKey);
  237. // 分段加密
  238. int blockSize = (mode == Cipher.ENCRYPT_MODE) ? RsaConst.ENCRYPT_KEYSIZE : RsaConst.DECRYPT_KEYSIZE;
  239. byte[] encryptedData = null;
  240. for (int i = 0; i < srcData.length; i += blockSize) {
  241. // 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
  242. byte[] doFinal = cipher.doFinal(subarray(srcData, i, i + blockSize));
  243. encryptedData = addAll(encryptedData, doFinal);
  244. }
  245. return encryptedData;
  246. } catch (NoSuchAlgorithmException e) {
  247. // //log.error("公钥算法-不存在的解密算法:", e);
  248. } catch (NoSuchPaddingException e) {
  249. // //log.error("公钥算法-无效的补位算法:", e);
  250. } catch (IllegalBlockSizeException e) {
  251. // //log.error("公钥算法-无效的块大小:", e);
  252. } catch (BadPaddingException e) {
  253. // //log.error("公钥算法-补位算法异常:", e);
  254. } catch (InvalidKeyException e) {
  255. // //log.error("公钥算法-无效的私钥:", e);
  256. }
  257. return null;
  258. }
  259. /**
  260. * 私钥算法
  261. *
  262. * @param srcData 源字节
  263. * @param privateKey 私钥
  264. * @param mode 加密 OR 解密
  265. * @return
  266. */
  267. public static byte[] rsaByPrivateKey(byte[] srcData, PrivateKey privateKey, int mode) {
  268. try {
  269. Cipher cipher = Cipher.getInstance(RsaConst.RSA_CHIPER);
  270. cipher.init(mode, privateKey);
  271. // 分段加密
  272. int blockSize = (mode == Cipher.ENCRYPT_MODE) ? RsaConst.ENCRYPT_KEYSIZE : RsaConst.DECRYPT_KEYSIZE;
  273. byte[] decryptData = null;
  274. for (int i = 0; i < srcData.length; i += blockSize) {
  275. byte[] doFinal = cipher.doFinal(subarray(srcData, i, i + blockSize));
  276. decryptData = addAll(decryptData, doFinal);
  277. }
  278. return decryptData;
  279. } catch (NoSuchAlgorithmException e) {
  280. // //log.error("私钥算法-不存在的解密算法:", e);
  281. } catch (NoSuchPaddingException e) {
  282. // log.error("私钥算法-无效的补位算法:", e);
  283. } catch (IllegalBlockSizeException e) {
  284. // log.error("私钥算法-无效的块大小:", e);
  285. } catch (BadPaddingException e) {
  286. // log.error("私钥算法-补位算法异常:", e);
  287. } catch (InvalidKeyException e) {
  288. // log.error("私钥算法-无效的私钥:", e);
  289. }
  290. return null;
  291. }
  292. // /////////////==========================
  293. public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
  294. if (array == null) {
  295. return null;
  296. }
  297. if (startIndexInclusive < 0) {
  298. startIndexInclusive = 0;
  299. }
  300. if (endIndexExclusive > array.length) {
  301. endIndexExclusive = array.length;
  302. }
  303. int newSize = endIndexExclusive - startIndexInclusive;
  304. if (newSize <= 0) {
  305. return new byte[0];
  306. }
  307. byte[] subarray = new byte[newSize];
  308. System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
  309. return subarray;
  310. }
  311. public static byte[] addAll(byte[] array1, byte[] array2) {
  312. if (array1 == null) {
  313. return clone(array2);
  314. } else if (array2 == null) {
  315. return clone(array1);
  316. }
  317. byte[] joinedArray = new byte[array1.length + array2.length];
  318. System.arraycopy(array1, 0, joinedArray, 0, array1.length);
  319. System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
  320. return joinedArray;
  321. }
  322. public static byte[] clone(byte[] array) {
  323. if (array == null) {
  324. return null;
  325. }
  326. return (byte[]) array.clone();
  327. }
  328. public static void log(String msg) {
  329. System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg);
  330. }
  331. }

RsaReadUtil.java

  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.StringReader;
  8. import java.security.KeyStore;
  9. import java.security.KeyStoreException;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.security.PrivateKey;
  12. import java.security.PublicKey;
  13. import java.security.UnrecoverableKeyException;
  14. import java.security.cert.Certificate;
  15. import java.security.cert.CertificateException;
  16. import java.security.cert.CertificateFactory;
  17. import java.util.Enumeration;
  18. import sun.misc.BASE64Decoder;
  19. //import com.jweb.//log.Logger;
  20. /**
  21. * <b>公私钥读取工具</b><br>
  22. * <br>
  23. *
  24. * @author 行者
  25. * @version 4.1.0
  26. */
  27. public final class RsaReadUtil {
  28. /**
  29. * 根据Cer文件读取公钥
  30. *
  31. * @param pubCerPath
  32. * @return
  33. */
  34. public static PublicKey getPublicKeyFromFile(String pubCerPath) {
  35. FileInputStream pubKeyStream = null;
  36. try {
  37. pubKeyStream = new FileInputStream(pubCerPath);
  38. byte[] reads = new byte[pubKeyStream.available()];
  39. pubKeyStream.read(reads);
  40. return getPublicKeyByText(new String(reads));
  41. } catch (FileNotFoundException e) {
  42. // //log.error("公钥文件不存在:", e);
  43. } catch (IOException e) {
  44. // log.error("公钥文件读取失败:", e);
  45. } finally {
  46. if (pubKeyStream != null) {
  47. try {
  48. pubKeyStream.close();
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. return null;
  55. }
  56. /**
  57. * 根据公钥Cer文本串读取公钥
  58. *
  59. * @param pubKeyText
  60. * @return
  61. */
  62. public static PublicKey getPublicKeyByText(String pubKeyText) {
  63. try {
  64. CertificateFactory certificateFactory = CertificateFactory.getInstance(RsaConst.KEY_X509);
  65. BufferedReader br = new BufferedReader(new StringReader(pubKeyText));
  66. String line = null;
  67. StringBuilder keyBuffer = new StringBuilder();
  68. while ((line = br.readLine()) != null) {
  69. if (!line.startsWith("-")) {
  70. keyBuffer.append(line);
  71. }
  72. }
  73. Certificate certificate = certificateFactory.generateCertificate(
  74. new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(keyBuffer.toString())));
  75. return certificate.getPublicKey();
  76. } catch (Exception e) {
  77. // log.error("解析公钥内容失败:", e);
  78. }
  79. return null;
  80. }
  81. /**
  82. * 根据私钥路径读取私钥
  83. *
  84. * @param pfxPath
  85. * @param priKeyPass
  86. * @return
  87. */
  88. public static PrivateKey getPrivateKeyFromFile(String pfxPath, String priKeyPass) {
  89. InputStream priKeyStream = null;
  90. try {
  91. priKeyStream = new FileInputStream(pfxPath);
  92. byte[] reads = new byte[priKeyStream.available()];
  93. priKeyStream.read(reads);
  94. return getPrivateKeyByStream(reads, priKeyPass);
  95. } catch (Exception e) {
  96. // log.error("解析文件,读取私钥失败:", e);
  97. } finally {
  98. if (priKeyStream != null) {
  99. try {
  100. priKeyStream.close();
  101. } catch (Exception e) {
  102. //
  103. }
  104. }
  105. }
  106. return null;
  107. }
  108. /**
  109. * 根据PFX私钥字节流读取私钥
  110. *
  111. * @param pfxBytes
  112. * @param priKeyPass
  113. * @return
  114. */
  115. public static PrivateKey getPrivateKeyByStream(byte[] pfxBytes, String priKeyPass) {
  116. try {
  117. KeyStore ks = KeyStore.getInstance(RsaConst.KEY_PKCS12);
  118. char[] charPriKeyPass = priKeyPass.toCharArray();
  119. ks.load(new ByteArrayInputStream(pfxBytes), charPriKeyPass);
  120. Enumeration<String> aliasEnum = ks.aliases();
  121. String keyAlias = null;
  122. if (aliasEnum.hasMoreElements()) {
  123. keyAlias = (String) aliasEnum.nextElement();
  124. }
  125. return (PrivateKey) ks.getKey(keyAlias, charPriKeyPass);
  126. } catch (IOException e) {
  127. // 加密失败
  128. // log.error("解析文件,读取私钥失败:", e);
  129. } catch (KeyStoreException e) {
  130. // log.error("私钥存储异常:", e);
  131. } catch (NoSuchAlgorithmException e) {
  132. // log.error("不存在的解密算法:", e);
  133. } catch (CertificateException e) {
  134. // log.error("证书异常:", e);
  135. } catch (UnrecoverableKeyException e) {
  136. // log.error("不可恢复的秘钥异常", e);
  137. }
  138. return null;
  139. }
  140. }

RsaConst.java

  1. public final class RsaConst {
  2. /** 编码 */
  3. public final static String ENCODE = "UTF-8";
  4. public final static String KEY_X509 = "X509";
  5. public final static String KEY_PKCS12 = "PKCS12";
  6. public final static String KEY_ALGORITHM = "RSA";
  7. public final static String CER_ALGORITHM = "MD5WithRSA";
  8. public final static String RSA_CHIPER = "RSA/ECB/PKCS1Padding";
  9. public final static int KEY_SIZE = 1024;
  10. /** 1024bit 加密块 大小 */
  11. public final static int ENCRYPT_KEYSIZE = 117;
  12. /** 1024bit 解密块 大小 */
  13. public final static int DECRYPT_KEYSIZE = 128;
  14. }

FormatUtil.java

  1. import java.math.BigDecimal;
  2. import java.text.DecimalFormat;
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.HashSet;
  7. import java.util.Iterator;
  8. import java.util.List;
  9. import java.util.Set;
  10. public final class FormatUtil {
  11. /** ==============IS Base=================== */
  12. /** 判断是否为整数(包括负数) */
  13. public static boolean isNumber(Object arg) {
  14. return NumberBo(0, toString(arg));
  15. }
  16. /** 判断是否为小数(包括整数,包括负数) */
  17. public static boolean isDecimal(Object arg) {
  18. return NumberBo(1, toString(arg));
  19. }
  20. /** 判断是否为空 ,为空返回true */
  21. public static boolean isEmpty(Object arg) {
  22. return toStringTrim(arg).length() == 0 ? true : false;
  23. }
  24. /** ==============TO Base=================== */
  25. /**
  26. * Object 转换成 Int 转换失败 返回默认值 0 <br>
  27. * 使用:toInt(值,默认值[选填])
  28. */
  29. public static int toInt(Object... args) {
  30. int def = 0;
  31. if (args != null) {
  32. String str = toStringTrim(args[0]);
  33. // 判断小数情况。舍弃小数位
  34. int stri = str.indexOf('.');
  35. str = stri > 0 ? str.substring(0, stri) : str;
  36. if (args.length > 1)
  37. def = Integer.parseInt(args[args.length - 1].toString());
  38. if (isNumber(str))
  39. return Integer.parseInt(str);
  40. }
  41. return def;
  42. }
  43. /**
  44. * Object 转换成 Long 转换失败 返回默认值 0 <br>
  45. * 使用:toLong(值,默认值[选填])
  46. */
  47. public static long toLong(Object... args) {
  48. Long def = 0L;
  49. if (args != null) {
  50. String str = toStringTrim(args[0]);
  51. if (args.length > 1)
  52. def = Long.parseLong(args[args.length - 1].toString());
  53. if (isNumber(str))
  54. return Long.parseLong(str);
  55. }
  56. return def;
  57. }
  58. /**
  59. * Object 转换成 Double 转换失败 返回默认值 0 <br>
  60. * 使用:toDouble(值,默认值[选填])
  61. */
  62. public static double toDouble(Object... args) {
  63. double def = 0;
  64. if (args != null) {
  65. String str = toStringTrim(args[0]);
  66. if (args.length > 1)
  67. def = Double.parseDouble(args[args.length - 1].toString());
  68. if (isDecimal(str))
  69. return Double.parseDouble(str);
  70. }
  71. return def;
  72. }
  73. /**
  74. * Object 转换成 BigDecimal 转换失败 返回默认值 0 <br>
  75. * 使用:toDecimal(值,默认值[选填]) 特别注意: new BigDecimal(Double) 会有误差,得先转String
  76. */
  77. public static BigDecimal toDecimal(Object... args) {
  78. return new BigDecimal(Double.toString(toDouble(args)));
  79. }
  80. /**
  81. * Object 转换成 Boolean 转换失败 返回默认值 false <br>
  82. * 使用:toBoolean(值,默认值[选填])
  83. */
  84. public static boolean toBoolean(String bool) {
  85. if (isEmpty(bool) || (!bool.equals("1") && !bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("ok")))
  86. return false;
  87. else
  88. return true;
  89. }
  90. /**
  91. * Object 转换成 String 为null 返回空字符 <br>
  92. * 使用:toString(值,默认值[选填])
  93. */
  94. public static String toString(Object... args) {
  95. String def = "";
  96. if (args != null) {
  97. if (args.length > 1)
  98. def = toString(args[args.length - 1]);
  99. Object obj = args[0];
  100. if (obj == null)
  101. return def;
  102. return obj.toString();
  103. } else {
  104. return def;
  105. }
  106. }
  107. /**
  108. * Object 转换成 String[去除所以空格]; 为null 返回空字符 <br>
  109. * 使用:toStringTrim(值,默认值[选填])
  110. */
  111. public static String toStringTrim(Object... args) {
  112. String str = toString(args);
  113. return str.replaceAll("\\s*", "");
  114. }
  115. /** ==============Other Base=================== */
  116. public static String getNowTime() {
  117. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
  118. }
  119. /** 数字左边补0 ,obj:要补0的数, length:补0后的长度 */
  120. public static String leftPad(Object obj, int length) {
  121. return String.format("%0" + length + "d", toInt(obj));
  122. }
  123. /** 小数 转 百分数 */
  124. public static String toPercent(Double str) {
  125. StringBuffer sb = new StringBuffer(Double.toString(str * 100.0000d));
  126. return sb.append("%").toString();
  127. }
  128. /** 百分数 转 小数 */
  129. public static Double toPercent2(String str) {
  130. if (str.charAt(str.length() - 1) == '%')
  131. return Double.parseDouble(str.substring(0, str.length() - 1)) / 100.0000d;
  132. return 0d;
  133. }
  134. /**
  135. * 将byte[] 转换成字符串
  136. */
  137. public static String byte2Hex(byte[] srcBytes) {
  138. StringBuilder hexRetSB = new StringBuilder();
  139. for (byte b : srcBytes) {
  140. String hexString = Integer.toHexString(0x00ff & b);
  141. hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
  142. }
  143. return hexRetSB.toString();
  144. }
  145. /**
  146. * 将16进制字符串转为转换成字符串
  147. */
  148. public static byte[] hex2Bytes(String source) {
  149. try {
  150. byte[] sourceBytes = new byte[source.length() / 2];
  151. for (int i = 0; i < sourceBytes.length; i++) {
  152. sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
  153. }
  154. return sourceBytes;
  155. } catch (NumberFormatException e) {
  156. log("转换出错" + e);
  157. throw new NumberFormatException();
  158. }
  159. }
  160. /** String 转 Money */
  161. public static String toMoney(Object str, String MoneyType) {
  162. DecimalFormat df = new DecimalFormat(MoneyType);
  163. if (isDecimal(str))
  164. return df.format(toDecimal(str)).toString();
  165. return df.format(toDecimal("0.00")).toString();
  166. }
  167. /** 获取字符串str 左边len位数 */
  168. public static String getLeft(Object obj, int len) {
  169. String str = toString(obj);
  170. if (len <= 0)
  171. return "";
  172. if (str.length() <= len)
  173. return str;
  174. else
  175. return str.substring(0, len);
  176. }
  177. /** 获取字符串str 右边len位数 */
  178. public static String getRight(Object obj, int len) {
  179. String str = toString(obj);
  180. if (len <= 0)
  181. return "";
  182. if (str.length() <= len)
  183. return str;
  184. else
  185. return str.substring(str.length() - len, str.length());
  186. }
  187. /**
  188. * 首字母变小写
  189. */
  190. public static String firstCharToLowerCase(String str) {
  191. Character firstChar = str.charAt(0);
  192. String tail = str.substring(1);
  193. str = Character.toLowerCase(firstChar) + tail;
  194. return str;
  195. }
  196. /**
  197. * 首字母变大写
  198. */
  199. public static String firstCharToUpperCase(String str) {
  200. Character firstChar = str.charAt(0);
  201. String tail = str.substring(1);
  202. str = Character.toUpperCase(firstChar) + tail;
  203. return str;
  204. }
  205. /**
  206. * List集合去除重复值 只能用于基本数据类型,。 对象类集合,自己写
  207. */
  208. @SuppressWarnings({ "rawtypes", "unchecked" })
  209. public static List delMoreList(List list) {
  210. Set set = new HashSet();
  211. List newList = new ArrayList();
  212. for (Iterator iter = list.iterator(); iter.hasNext();) {
  213. Object element = iter.next();
  214. if (set.add(element))
  215. newList.add(element);
  216. }
  217. return newList;
  218. }
  219. public static String formatParams(String message, Object[] params) {
  220. StringBuffer msg = new StringBuffer();
  221. String temp = "";
  222. for (int i = 0; i < params.length + 1; i++) {
  223. int j = message.indexOf("{}") + 2;
  224. if (j > 1) {
  225. temp = message.substring(0, j);
  226. temp = temp.replaceAll("\\{\\}", FormatUtil.toString(params[i]));
  227. msg.append(temp);
  228. message = message.substring(j);
  229. } else {
  230. msg.append(message);
  231. message = "";
  232. }
  233. }
  234. return msg.toString();
  235. }
  236. /** ============== END =================== */
  237. public final static class MoneyType {
  238. /** * 保留2位有效数字,整数位每3位逗号隔开 (默认) */
  239. public static final String DECIMAL = "#,##0.00";
  240. /** * 保留2位有效数字 */
  241. public static final String DECIMAL_2 = "0.00";
  242. /** * 保留4位有效数字 */
  243. public static final String DECIMAL_4 = "0.0000";
  244. }
  245. private static boolean NumberBo(int type, Object obj) {
  246. if (isEmpty(obj))
  247. return false;
  248. int points = 0;
  249. int chr = 0;
  250. String str = toString(obj);
  251. for (int i = str.length(); --i >= 0;) {
  252. chr = str.charAt(i);
  253. if (chr < 48 || chr > 57) { // 判断数字
  254. if (i == 0 && chr == 45) // 判断 - 号
  255. return true;
  256. if (i >= 0 && chr == 46 && type == 1) { // 判断 . 号
  257. ++points;
  258. if (points <= 1)
  259. continue;
  260. }
  261. return false;
  262. }
  263. }
  264. return true;
  265. }
  266. public static void log(String msg) {
  267. System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg);
  268. }
  269. }
文档更新时间: 2019-06-17 14:44   作者:support