123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- package cn.efunbox.base.util;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.codec.binary.Hex;
- import sun.misc.BASE64Decoder;
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
- import java.io.UnsupportedEncodingException;
- import java.lang.reflect.Field;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.*;
- /**
- * 常見的几种加密方式
- */
- @Slf4j
- public class Encrypt {
- public static final String SIGN = "sign";
- public static String createSHA256Sign(Map<String, Object> paramMap, String signKey) {
- List<String> sortedKeys = new ArrayList<String>();
- for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
- if (SIGN.equals(entry.getKey())) {
- continue;
- }
- sortedKeys.add(entry.getKey());
- }
- if (sortedKeys.size() == 0) {
- // 没有参数
- return "";
- }
- Collections.sort(sortedKeys);
- StringBuffer buff = new StringBuffer("");
- for (String key : sortedKeys) {
- Object val = paramMap.get(key);
- if (Objects.isNull(val)) {
- continue;
- }
- buff.append(key).append("=").append(val).append("&");
- }
- buff.deleteCharAt(buff.length()-1);
- buff.append(signKey);
- try {
- return Encrypt.String2SHA256(buff.toString());
- } catch (Exception e) {
- throw new RuntimeException("签名错误");
- }
- }
- public static String createOutSideSHA256Sign(Map<String, Object> paramMap, String signKey) {
- List<String> sortedKeys = new ArrayList<>();
- for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
- if (SIGN.equals(entry.getKey())) {
- continue;
- }
- sortedKeys.add(entry.getKey());
- }
- if (sortedKeys.size() == 0) {
- // 没有参数
- return "";
- }
- Collections.sort(sortedKeys);
- StringBuffer buff = new StringBuffer("");
- for (String key : sortedKeys) {
- Object val = paramMap.get(key);
- if (Objects.isNull(val)) {
- continue;
- }
- buff.append(key).append("=").append(val).append("&");
- }
- buff.append("sign=");
- buff.append(signKey);
- try {
- return Encrypt.String2SHA256(buff.toString());
- } catch (Exception e) {
- throw new RuntimeException("签名错误");
- }
- }
- /**
- * 利用Apache的工具类实现SHA-256加密
- * @param str 加密后的报文
- * @return
- */
- public static String String2SHA256(String str){
- MessageDigest messageDigest;
- String encdeStr = "";
- try {
- messageDigest = MessageDigest.getInstance("SHA-256");
- byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
- encdeStr = Hex.encodeHexString(hash);
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return encdeStr;
- }
- //---------
- /**
- * 利用java原生的摘要实现SHA256加密
- * @param str 加密后的报文
- * @return
- */
- public static String String2SHA256StrJava(String str){
- MessageDigest messageDigest;
- String encodeStr = "";
- try {
- messageDigest = MessageDigest.getInstance("SHA-256");
- messageDigest.update(str.getBytes("UTF-8"));
- encodeStr = byte2Hex(messageDigest.digest());
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return encodeStr;
- }
-
- /**
- * 将byte转为16进制
- * @param bytes
- * @return
- */
- private static String byte2Hex(byte[] bytes){
- StringBuffer stringBuffer = new StringBuffer();
- String temp = null;
- for (int i=0;i<bytes.length;i++){
- temp = Integer.toHexString(bytes[i] & 0xFF);
- if (temp.length()==1){
- //1得到一位的进行补0操作
- stringBuffer.append("0");
- }
- stringBuffer.append(temp);
- }
- return stringBuffer.toString();
- }
- public static Map<String,Object> objectToMap(Object obj) throws Exception {
- if(obj == null){
- return null;
- }
- Map<String, Object> map = new HashMap<String, Object>();
- Field[] declaredFields = obj.getClass().getDeclaredFields();
- for (Field field : declaredFields){
- field.setAccessible(true);
- map.put(field.getName(), field.get(obj));
- }
- return map;
- }
- /**
- * SHA1加密
- * @param arr
- * @return
- */
- public static String createSHA1Sign(String... arr) {
- try {
- Arrays.sort(arr);
- StringBuilder content = new StringBuilder();
- for (int i = 0; i < arr.length; i++) {
- content.append(arr[i]);
- }
- MessageDigest md = MessageDigest.getInstance("SHA-1");
- byte[] digest = md.digest(content.toString().getBytes());
- return byte2Hex(digest);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * AES 加密
- * 参考 https://www.cnblogs.com/sunliyuan/p/11130446.html
- * @return
- * @throws Exception
- */
- public static String encrypt(String data,String key) throws Exception {
- try {
- Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
- int blockSize = cipher.getBlockSize();
- byte[] dataBytes = data.getBytes();
- int plaintextLength = dataBytes.length;
- if (plaintextLength % blockSize != 0) {
- plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
- }
- byte[] plaintext = new byte[plaintextLength];
- System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
- SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
- cipher.init(Cipher.ENCRYPT_MODE, keyspec);
- byte[] encrypted = cipher.doFinal(plaintext);
- return new sun.misc.BASE64Encoder().encode(encrypted);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- /**
- * AES解密
- * 参考 https://www.cnblogs.com/sunliyuan/p/11130446.html
- * @param data 待解密内容
- * @param key 密钥
- * @return
- * @throws Exception
- */
- public static String desEncrypt(String data,String key) throws Exception {
- try {
- byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
- Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
- SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
- cipher.init(Cipher.DECRYPT_MODE, keyspec);
- byte[] original = cipher.doFinal(encrypted1);
- String originalString = new String(original);
- return originalString;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- public static void main(String[] args) throws Exception {
- //String signature = "20200114_86570b47-1ac7-532f-531c-4e761f322ce9_efunbox_sRTI2TEFENNZRu2fyEArvhn9giX0QHTze08cV/onriU=";
- //System.out.println(createSHA1Sign(signature));
- //System.out.println(desEncrypt("ps0MIFj3jQzh/swEr5v3SmzZyOfeg7+ghbyGTn7MS4I=","efunbox_xyyfxxbg"));
- // System.out.println(encrypt("===","efunbox_xyyfxxbg"));
- // System.out.println(desEncrypt("JbeqomEM1MoPWVE0tcK5FA==","efunbox_xyyfxxbg"));
- }
- }
|