From 6a88e788e7bed0957fc77e06341a2fa6ea7b14ac Mon Sep 17 00:00:00 2001 From: liuhz <9200656762@qq.com> Date: Fri, 6 Aug 2021 13:05:53 +0800 Subject: [PATCH] update --- .../com/ydool/boot/api/util/CodecUtils.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/main/java/com/ydool/boot/api/util/CodecUtils.java diff --git a/src/main/java/com/ydool/boot/api/util/CodecUtils.java b/src/main/java/com/ydool/boot/api/util/CodecUtils.java new file mode 100644 index 0000000..0839d94 --- /dev/null +++ b/src/main/java/com/ydool/boot/api/util/CodecUtils.java @@ -0,0 +1,87 @@ +package com.ydool.boot.api.util; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import org.springframework.util.ObjectUtils; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; + +/** + * Created with IntelliJ IDEA. + * User: liuj + * Date: 2020/11/18 + * Time: 13:27 + * Description: No Description + */ +public class CodecUtils { + + private static Cipher encryptCipher; // 加密cipher + private static Cipher decryptChipher; // 解密chipher + private static final String ENCODING = "UTF-8"; + + static { + try { + encryptCipher = Cipher.getInstance("AES"); + decryptChipher = Cipher.getInstance("AES"); + encryptCipher.init(Cipher.ENCRYPT_MODE, generateAESKey("ydool", ENCODING)); + decryptChipher.init(Cipher.DECRYPT_MODE, generateAESKey("ydool", ENCODING)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static SecretKeySpec generateAESKey(final String key, final String encoding) { + try { + final byte[] finalKey = new byte[16]; + int i = 0; + for (byte b : key.getBytes(encoding)) + finalKey[i++ % 16] ^= b; + return new SecretKeySpec(finalKey, "AES"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + /** + * 加密算法 + * + * @param encryptString + * @return + */ + public static String encrypt(String encryptString) { + try { + if(encryptString == null) return null; + return new String(Hex.encodeHex(encryptCipher.doFinal(encryptString.getBytes(ENCODING)))).toUpperCase(); + } catch (BadPaddingException e) { + throw new RuntimeException(e); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } catch (IllegalBlockSizeException e) { + throw new RuntimeException(e); + } + } + + /** + * 解密算法 + * + * @param decryptString + * @return + */ + public static String decrypt(String decryptString) { + + if(ObjectUtils.isEmpty(decryptString)) return null; + try { + return new String(decryptChipher.doFinal(Hex.decodeHex(decryptString.toCharArray()))); + } catch (DecoderException nspe) { + throw new RuntimeException(nspe); + } catch (BadPaddingException nsae) { + throw new RuntimeException(nsae); + } catch (IllegalBlockSizeException ike) { + throw new RuntimeException(ike); + } + } +}