deason 4 years ago
parent
commit
2eab317298

+ 4 - 0
config-center-client/pom.xml

@@ -41,6 +41,10 @@
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
         </dependency>
+        <dependency>
+            <groupId>commons-codec</groupId>
+            <artifactId>commons-codec</artifactId>
+        </dependency>
     </dependencies>
 
     <dependencyManagement>

+ 79 - 0
config-center-client/src/main/java/cn/com/qmth/framework/config/center/client/utils/AESUtils.java

@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2021 the original author, All Rights Reserved.
+ * Created by Deason on 2021-04-29 22:19:33
+ */
+
+package cn.com.qmth.framework.config.center.client.utils;
+
+import org.apache.commons.codec.binary.Hex;
+import org.apache.commons.lang3.StringUtils;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * AES加、解密
+ *
+ * @author: Deason
+ * @since: 2021/4/29
+ */
+public class AESUtils {
+
+    private static final String AES = "AES";
+
+    private static final String AES_CBC_PKCS5Padding = "AES/CBC/PKCS5Padding";
+
+    public static String encrypt(String key, String str) {
+        if (StringUtils.isEmpty(str)) {
+            return "";
+        }
+
+        SecretKey secretKey = AESUtils.initSecretKey(key);
+        key = StringUtils.rightPad(key, 18, (char) 48);
+        final byte[] iv = key.substring(2, 18).getBytes();
+
+        try {
+            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5Padding);
+            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
+
+            byte[] data = cipher.doFinal(str.getBytes());
+            return Hex.encodeHexString(data);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public static String decrypt(String key, String str) {
+        if (StringUtils.isEmpty(str)) {
+            return "";
+        }
+
+        SecretKey secretKey = AESUtils.initSecretKey(key);
+        key = StringUtils.rightPad(key, 18, (char) 48);
+        final byte[] iv = key.substring(2, 18).getBytes();
+
+        try {
+            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5Padding);
+            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
+
+            byte[] data = cipher.doFinal(Hex.decodeHex(str));
+            return new String(data);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static SecretKey initSecretKey(String key) {
+        if (key == null) {
+            throw new IllegalArgumentException("key must be not null");
+        }
+
+        byte[] keyBytes = key.getBytes();
+        byte[] newKeyBytes = new byte[16];
+        System.arraycopy(keyBytes, 0, newKeyBytes, 0, Math.min(keyBytes.length, 16));
+        return new SecretKeySpec(newKeyBytes, AES);
+    }
+
+}