Encrypt.java 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package cn.efunbox.base.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.commons.codec.binary.Hex;
  4. import sun.misc.BASE64Decoder;
  5. import javax.crypto.Cipher;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import java.io.UnsupportedEncodingException;
  8. import java.lang.reflect.Field;
  9. import java.security.MessageDigest;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.util.*;
  12. /**
  13. * 常見的几种加密方式
  14. */
  15. @Slf4j
  16. public class Encrypt {
  17. public static final String SIGN = "sign";
  18. public static String createSHA256Sign(Map<String, Object> paramMap, String signKey) {
  19. List<String> sortedKeys = new ArrayList<String>();
  20. for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
  21. if (SIGN.equals(entry.getKey())) {
  22. continue;
  23. }
  24. sortedKeys.add(entry.getKey());
  25. }
  26. if (sortedKeys.size() == 0) {
  27. // 没有参数
  28. return "";
  29. }
  30. Collections.sort(sortedKeys);
  31. StringBuffer buff = new StringBuffer("");
  32. for (String key : sortedKeys) {
  33. Object val = paramMap.get(key);
  34. if (Objects.isNull(val)) {
  35. continue;
  36. }
  37. buff.append(key).append("=").append(val).append("&");
  38. }
  39. buff.deleteCharAt(buff.length()-1);
  40. buff.append(signKey);
  41. try {
  42. return Encrypt.String2SHA256(buff.toString());
  43. } catch (Exception e) {
  44. throw new RuntimeException("签名错误");
  45. }
  46. }
  47. public static String createOutSideSHA256Sign(Map<String, Object> paramMap, String signKey) {
  48. List<String> sortedKeys = new ArrayList<>();
  49. for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
  50. if (SIGN.equals(entry.getKey())) {
  51. continue;
  52. }
  53. sortedKeys.add(entry.getKey());
  54. }
  55. if (sortedKeys.size() == 0) {
  56. // 没有参数
  57. return "";
  58. }
  59. Collections.sort(sortedKeys);
  60. StringBuffer buff = new StringBuffer("");
  61. for (String key : sortedKeys) {
  62. Object val = paramMap.get(key);
  63. if (Objects.isNull(val)) {
  64. continue;
  65. }
  66. buff.append(key).append("=").append(val).append("&");
  67. }
  68. buff.append("sign=");
  69. buff.append(signKey);
  70. try {
  71. return Encrypt.String2SHA256(buff.toString());
  72. } catch (Exception e) {
  73. throw new RuntimeException("签名错误");
  74. }
  75. }
  76. /**
  77. * 利用Apache的工具类实现SHA-256加密
  78. * @param str 加密后的报文
  79. * @return
  80. */
  81. public static String String2SHA256(String str){
  82. MessageDigest messageDigest;
  83. String encdeStr = "";
  84. try {
  85. messageDigest = MessageDigest.getInstance("SHA-256");
  86. byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
  87. encdeStr = Hex.encodeHexString(hash);
  88. } catch (NoSuchAlgorithmException e) {
  89. e.printStackTrace();
  90. } catch (UnsupportedEncodingException e) {
  91. e.printStackTrace();
  92. }
  93. return encdeStr;
  94. }
  95. //---------
  96. /**
  97. * 利用java原生的摘要实现SHA256加密
  98. * @param str 加密后的报文
  99. * @return
  100. */
  101. public static String String2SHA256StrJava(String str){
  102. MessageDigest messageDigest;
  103. String encodeStr = "";
  104. try {
  105. messageDigest = MessageDigest.getInstance("SHA-256");
  106. messageDigest.update(str.getBytes("UTF-8"));
  107. encodeStr = byte2Hex(messageDigest.digest());
  108. } catch (NoSuchAlgorithmException e) {
  109. e.printStackTrace();
  110. } catch (UnsupportedEncodingException e) {
  111. e.printStackTrace();
  112. }
  113. return encodeStr;
  114. }
  115. /**
  116. * 将byte转为16进制
  117. * @param bytes
  118. * @return
  119. */
  120. private static String byte2Hex(byte[] bytes){
  121. StringBuffer stringBuffer = new StringBuffer();
  122. String temp = null;
  123. for (int i=0;i<bytes.length;i++){
  124. temp = Integer.toHexString(bytes[i] & 0xFF);
  125. if (temp.length()==1){
  126. //1得到一位的进行补0操作
  127. stringBuffer.append("0");
  128. }
  129. stringBuffer.append(temp);
  130. }
  131. return stringBuffer.toString();
  132. }
  133. public static Map<String,Object> objectToMap(Object obj) throws Exception {
  134. if(obj == null){
  135. return null;
  136. }
  137. Map<String, Object> map = new HashMap<String, Object>();
  138. Field[] declaredFields = obj.getClass().getDeclaredFields();
  139. for (Field field : declaredFields){
  140. field.setAccessible(true);
  141. map.put(field.getName(), field.get(obj));
  142. }
  143. return map;
  144. }
  145. /**
  146. * SHA1加密
  147. * @param arr
  148. * @return
  149. */
  150. public static String createSHA1Sign(String... arr) {
  151. try {
  152. Arrays.sort(arr);
  153. StringBuilder content = new StringBuilder();
  154. for (int i = 0; i < arr.length; i++) {
  155. content.append(arr[i]);
  156. }
  157. MessageDigest md = MessageDigest.getInstance("SHA-1");
  158. byte[] digest = md.digest(content.toString().getBytes());
  159. return byte2Hex(digest);
  160. } catch (Exception e) {
  161. e.printStackTrace();
  162. }
  163. return null;
  164. }
  165. /**
  166. * AES 加密
  167. * 参考 https://www.cnblogs.com/sunliyuan/p/11130446.html
  168. * @return
  169. * @throws Exception
  170. */
  171. public static String encrypt(String data,String key) throws Exception {
  172. try {
  173. Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
  174. int blockSize = cipher.getBlockSize();
  175. byte[] dataBytes = data.getBytes();
  176. int plaintextLength = dataBytes.length;
  177. if (plaintextLength % blockSize != 0) {
  178. plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
  179. }
  180. byte[] plaintext = new byte[plaintextLength];
  181. System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
  182. SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  183. cipher.init(Cipher.ENCRYPT_MODE, keyspec);
  184. byte[] encrypted = cipher.doFinal(plaintext);
  185. return new sun.misc.BASE64Encoder().encode(encrypted);
  186. } catch (Exception e) {
  187. e.printStackTrace();
  188. return null;
  189. }
  190. }
  191. /**
  192. * AES解密
  193. * 参考 https://www.cnblogs.com/sunliyuan/p/11130446.html
  194. * @param data 待解密内容
  195. * @param key 密钥
  196. * @return
  197. * @throws Exception
  198. */
  199. public static String desEncrypt(String data,String key) throws Exception {
  200. try {
  201. byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
  202. Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
  203. SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  204. cipher.init(Cipher.DECRYPT_MODE, keyspec);
  205. byte[] original = cipher.doFinal(encrypted1);
  206. String originalString = new String(original);
  207. return originalString;
  208. } catch (Exception e) {
  209. e.printStackTrace();
  210. return null;
  211. }
  212. }
  213. public static void main(String[] args) throws Exception {
  214. //String signature = "20200114_86570b47-1ac7-532f-531c-4e761f322ce9_efunbox_sRTI2TEFENNZRu2fyEArvhn9giX0QHTze08cV/onriU=";
  215. //System.out.println(createSHA1Sign(signature));
  216. //System.out.println(desEncrypt("ps0MIFj3jQzh/swEr5v3SmzZyOfeg7+ghbyGTn7MS4I=","efunbox_xyyfxxbg"));
  217. // System.out.println(encrypt("===","efunbox_xyyfxxbg"));
  218. // System.out.println(desEncrypt("JbeqomEM1MoPWVE0tcK5FA==","efunbox_xyyfxxbg"));
  219. }
  220. }