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