Java / MySQL 的 AES-128-ECB加密


使用AES aes-128-ecb

1、Java 工具類加解密

工具類 :

  1 package com.pro.tx.util;
  2 
  3 import org.apache.commons.codec.binary.Base64;
  4 import org.slf4j.Logger;
  5 import org.slf4j.LoggerFactory;
  6 import javax.crypto.Cipher;
  7 import javax.crypto.spec.SecretKeySpec;
  8 
  9 /**
 10  * @author 
 11  * @title: AESUtil
 12  * @description: AES 加解密公共類 使用AES-128-ECB加密模式
 13  * @date 2019/7/11 19:43
 14  */
 15 public class AESUtil {
 16 
 17     private static final Logger logger =
 18                     LoggerFactory.getLogger(AESUtil.class);
 19 
 20     /** AES 加解密密鑰,請勿擅自修改!!! */
 21     private static final String key = "0000000000000000";
 22 
 23 
 24     /**
 25      * AES 加密 使用AES-128-ECB加密模式
 26      * @param sSrc  需要加密的字段
 27      * @param sKey  16 位密鑰
 28      * @return
 29      * @throws Exception
 30      */
 31     public static String Encrypt(String sSrc, String sKey) {
 32         try {
 33             if (sKey == null) {
 34                 logger.info("Key為空null");
 35                 return null;
 36             }
 37             /** 判斷Key是否為16位 */
 38             if (sKey.length() != 16) {
 39                 logger.info("Key長度不是16位");
 40                 return null;
 41             }
 42             byte[] raw = sKey.getBytes("utf-8");
 43             SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
 44             /** "算法/模式/補碼方式" */
 45             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
 46             cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
 47             byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
 48             /** 此處使用BASE64做轉碼功能,同時能起到2次加密的作用。 */
 49             return new Base64().encodeToString(encrypted);
 50         } catch (Exception e) {
 51            logger.info(sSrc + " AES解密異常!");
 52            e.printStackTrace();
 53            return null;
 54         }
 55     }
 56 
 57     public static String Encrypt(String sSrc) {
 58         return Encrypt(sSrc, key);
 59     }
 60 
 61     /**
 62      * AES 解密 使用AES-128-ECB加密模式
 63      * @param sSrc  需要解密的字段
 64      * @param sKey  16 位密鑰
 65      * @return
 66      * @throws Exception
 67      */
 68     public static String Decrypt(String sSrc, String sKey) {
 69         try {
 70             // 判斷Key是否正確
 71             if (sKey == null) {
 72                 logger.info("Key為空null");
 73                 return null;
 74             }
 75             // 判斷Key是否為16位
 76             if (sKey.length() != 16) {
 77                 logger.info("Key長度不是16位");
 78                 return null;
 79             }
 80             byte[] raw = sKey.getBytes("utf-8");
 81             SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
 82             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
 83             cipher.init(Cipher.DECRYPT_MODE, skeySpec);
 84             /** 先用base64解密 */
 85             byte[] encrypted1 = new Base64().decode(sSrc);
 86             try {
 87                 byte[] original = cipher.doFinal(encrypted1);
 88                 String originalString = new String(original,"utf-8");
 89                 return originalString;
 90             } catch (Exception e) {
 91                 System.out.println(e.toString());
 92                 return null;
 93             }
 94         } catch (Exception e) {
 95             logger.info(sSrc + " AES解密異常!");
 96             e.printStackTrace();
 97             return null;
 98         }
 99     }
100 
101 
102     public static String Decrypt(String sSrc) {
103         return Decrypt(sSrc, key);
104     }
105 
106 }

工具類加解密驗證 :

 

2、MySQL 數據庫函數加解密

說明 :

mysql默認為 aes-128-ecb模式
加密函數 : TO_BASE64(AES_ENCRYPT(str, key, iv))
解密函數 : AES_DECRYPT(FROM_BASE64 (str),key, iv)
 
str:需要加解密的字符串; key:必須為16wei秘鑰,加解密的秘鑰需保持一致。 iv: 16位密鑰
 
TO_BASE6()與 FROM_BASE64()函數是base64的加解密,解決加解密過程中,中文亂碼的問題。

加密腳本測試 :

解密腳本測試 :

 

使用AES aes-128-cbc

1、Java 工具類加解密

工具類:

@Slf4j
public class EncryptUtils {
    // AES 相關
    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static SecretKey AES_CBC_KEY;
    private static IvParameterSpec AES_CBC_IV;
    private static Cipher aesEncryptCipher;
    private static Cipher aesDecryptCipher;

    /**
     * AES 加密
     * @param input 字符串
     * @return 成功返回密文字符串,base64 格式;失敗返回 null
     */
    public static String aesEncrypt(String input)  {
        // 第一次調用,初始化 cipher
        if (aesEncryptCipher == null) {
            try {
                aesEncryptCipher = Cipher.getInstance(AES_ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                return null;
            } catch (NoSuchPaddingException e) {
                return null;
            }
            try {
                aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesGetKey(), aesGetIv());
            } catch (InvalidKeyException e) {
                return null;
            } catch (InvalidAlgorithmParameterException e) {
                return null;
            }
        }

        // 使用 cipher 加密
        byte[] cipherText;
        try {
            cipherText = aesEncryptCipher.doFinal(input.getBytes(Charset.forName("UTF-8")));
        } catch (IllegalBlockSizeException e) {
            return null;
        } catch (BadPaddingException e) {
            return null;
        }
        return Base64.getEncoder()
                .encodeToString(cipherText);
    }

    /**
     * AES 解密
     * @param cipherText 密文,base64 格式字符串
     * @return 成功返回明文字符串;失敗返回 null
     */
    public static String aesDecrypt(String cipherText) {
        // 第一次調用,初始化 cipher
        if (aesDecryptCipher == null) {
            try {
                aesDecryptCipher = Cipher.getInstance(AES_ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                return null;
            } catch (NoSuchPaddingException e) {
                return null;
            }
            try {
                aesDecryptCipher.init(Cipher.DECRYPT_MODE, aesGetKey(), aesGetIv());
            } catch (InvalidKeyException e) {
                return null;
            } catch (InvalidAlgorithmParameterException e) {
                return null;
            }
        }

        // 使用 cipher 解密
        byte[] plainText;
        try {
            plainText = aesDecryptCipher.doFinal(Base64.getDecoder()
                    .decode(cipherText));
        } catch (IllegalBlockSizeException e) {
            return null;
        } catch (BadPaddingException e) {
            return null;
        }
        return new String(plainText, Charset.forName("UTF-8"));
    }
}

2、MySQL 數據庫函數加解密

說明 :

mysql5.5及以下的版本僅支持aes-128-ecb模式,如果需要其它模式需要mysql5.6及以上版本才支持,可通過mysql全局變量如下方式指定:

SET block_encryption_mode = 'aes-256-cbc';

例如,我要做aes-128-cbc的加密,可參考下面的sql:

加密

#設置加密模式
SET block_encryption_mode = 'AES-128-CBC'; 
#設置偏移量 16位(AES128為128位bit,轉成byte字符)
SET @Iv  = '1234567890123412';
#設置秘鑰 16位(AES128為128位bit,轉成byte字符)
SET @Key = '7777777777723412';
SELECT to_base64(AES_ENCRYPT('22222',@key,@Iv)) as ENCRYPT;

解密

SET block_encryption_mode = 'AES-128-CBC';
SET @Iv  = '1234567890123412';
SET @Key = 'ccccccc';
SELECT AES_DECRYPT(FROM_base64('uroLJan2lqQ53UmzGj2sTA=='),@key,@Iv) as DECRYPT;

 

SET block_encryption_mode = 'AES-128-CBC';
SET @Iv  = '1234567890123412';
SET @Key = 'ccccccc';
SELECT AES_DECRYPT(FROM_base64('uroLJan2lqQ53UmzGj2sTA=='),@key,@Iv) as DECRYPT;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM