Selaa lähdekoodia

更新AES加解密逻辑

woody 1 vuosi sitten
vanhempi
commit
6013bca603

+ 47 - 3
framework-base/src/main/java/com/chelvc/framework/base/util/AESUtils.java

@@ -32,9 +32,14 @@ public final class AESUtils {
     public static final String ALGORITHM = "AES";
 
     /**
-     * 密码处理器算法
+     * CBC密码处理器算法
      */
-    public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
+    public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
+
+    /**
+     * ECB密码处理器算法
+     */
+    public static final String ECB_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
 
     static {
         Security.addProvider(new BouncyCastleProvider());
@@ -69,6 +74,23 @@ public final class AESUtils {
         return offset == 8 ? key : StringUtils.rjust(key, key.length() + offset, '0');
     }
 
+    /**
+     * 获取密码处理器
+     *
+     * @param mode   加解密模式
+     * @param secret 密钥
+     * @return 密码处理器实例
+     */
+    public static Cipher getCipher(int mode, @NonNull String secret) {
+        try {
+            Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM);
+            cipher.init(mode, new SecretKeySpec(Base64.decodeBase64(secret), ALGORITHM));
+            return cipher;
+        } catch (GeneralSecurityException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     /**
      * 获取密码处理器
      *
@@ -79,7 +101,7 @@ public final class AESUtils {
      */
     public static Cipher getCipher(int mode, @NonNull String secret, @NonNull String iv) {
         try {
-            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
             Key key = new SecretKeySpec(Base64.decodeBase64(secret), ALGORITHM);
             AlgorithmParameters parameters = AlgorithmParameters.getInstance(ALGORITHM);
             parameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
@@ -108,6 +130,17 @@ public final class AESUtils {
         }
     }
 
+    /**
+     * AES加密
+     *
+     * @param original 明文
+     * @param secret   密钥
+     * @return 密文(base64)
+     */
+    public static String encode(String original, @NonNull String secret) {
+        return original == null ? null : encode(getCipher(Cipher.ENCRYPT_MODE, secret), original);
+    }
+
     /**
      * AES加密
      *
@@ -138,6 +171,17 @@ public final class AESUtils {
         }
     }
 
+    /**
+     * AES解密
+     *
+     * @param ciphertext 密文(base64)
+     * @param secret     密钥
+     * @return 明文
+     */
+    public static String decode(String ciphertext, String secret) {
+        return ciphertext == null ? null : decode(getCipher(Cipher.DECRYPT_MODE, secret), ciphertext);
+    }
+
     /**
      * AES解密
      *