AES加解密工具类

Posted 格子衫111

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES加解密工具类相关的知识,希望对你有一定的参考价值。

1、加载pom依赖

<!-- 加载配置文件工具类需要 -->
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.9</version>
        </dependency>

<!--  Base64转码需要 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>

2、配置文件配置token

application.yml

#AES加解密所需token,自定义16位字符串
encry.token: 1234567890123456

3、编写工具类

PropUtils.java

package com.zwt.utils.properties;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * 加载配置文件工具类
 */
public class PropUtils 
    private PropertiesConfiguration props = null;

    private static class LazyHolder 
        public static final PropUtils instance = new PropUtils();
    

    public static PropUtils getInstance() 
        return LazyHolder.instance;
    

    private PropUtils() 
        try 
        //加载application.yml配置文件,这里需要根据项目替换
            props = new PropertiesConfiguration("application.yml");
            props.setThrowExceptionOnMissing(true);
         catch (ConfigurationException e) 
            throw new RuntimeException(String.format("Failed to load application.yml.[exception = %s]", e.getMessage()), e);
        
    

    public String getString(String key) 
        return props.getString(key);
    

    public String getString(String key, String defaultValue) 
        return props.getString(key, defaultValue);
    

    public int getInt(String key) 
        return props.getInt(key);
    

    public int getInt(String key, int defaultValue) 
        return props.getInt(key, defaultValue);
    

    public String[] getStringArray(String key) 
        return props.getStringArray(key);
    

    public boolean getBoolean(String key, boolean defaultValue) 
        return props.getBoolean(key, defaultValue);
    

    public short getShort(String key, Short defaultValue) 
        return props.getShort(key, defaultValue);
    

    public Object getProperty(String key)
        return props.getProperty(key);
    

EncryptUtils.java

package com.zwt.utils;

import com.zwt.utils.properties.PropUtils;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * AES加解密工具类
 */
public class EncryptUtils 

    private static final Logger log = LoggerFactory.getLogger(EncryptUtils.class);

    private static String TOKEN;

    static 
        PropUtils config = PropUtils.getInstance();
        TOKEN = config.getString("encry.token");
        if (TOKEN == null || TOKEN.trim().length() != 16) 
            TOKEN = null;
            throw new RuntimeException(
                    "Invalid token string! Token can't be blank and length must be 16!");
        
    

    private static final SecretKeySpec key = new SecretKeySpec(TOKEN.trim().getBytes(), "AES");

    private static String encodeBase64(byte[] msg) 
        Base64 encoder = new Base64();
        return encoder.encodeToString(msg);
    

    private static byte[] decodeBase64(String msg) 
        Base64 decoder = new Base64();
        return decoder.decode(msg);
    

    /**
     * 加密
     * @param p 明文
     * @return
     * @throws Exception
     */
    public static String encrypt(String p) throws Exception 
        if (TOKEN == null) 
            throw new RuntimeException("Can't encrypt password because token is invalid!");
        
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = p.getBytes("UTF-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(byteContent);
        return encodeBase64(result);
    

    /**
     * 解密
     * @param p 密文
     * @return
     * @throws Exception
     */
    public static String decrypt(String p) throws Exception 
        if (TOKEN == null) 
            throw new RuntimeException("Can't decrypt password because token is invalid!");
        
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(decodeBase64(p)), "UTF-8");
    

    /**
     * 加密
     * @param p 原文
     * @param token
     * @return
     * @throws Exception
     */
    public static String encrypt(String p, String token) throws Exception 
        SecretKeySpec key = new SecretKeySpec(token.trim().getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = p.getBytes("UTF-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(byteContent);
        return encodeBase64(result);
    

    /**
     * 解密
     * @param p 密文
     * @param token
     * @return
     * @throws Exception
     */
    public static String decrypt(String p, String token) throws Exception 
        SecretKeySpec key = new SecretKeySpec(token.trim().getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(decodeBase64(p)), "UTF-8");
    

    // 测试
    public static void main(String[] args) throws Exception 

        log.info("Please input original password: ");
        //原始字符串
        try (Scanner in = new Scanner(System.in)) 
            // 加密后
            String encryptedStr = encrypt(in.nextLine());
            log.info("Encrypted password: ", encryptedStr);

            //解密后:
            log.info("Original password: ", decrypt(encryptedStr));
         catch (Exception e) 
            log.error("Encrypt/Decrypt error:", e.getMessage());
        

    

4、运行结果

以上是关于AES加解密工具类的主要内容,如果未能解决你的问题,请参考以下文章

Java实现AES ECP PKCS5Padding加解密工具类

Java中的AES加解密工具类:AESUtils

AES加解密

java使用AES 工具类 加解密解决数据保密性问题

AES加解密 对称加密

python——rsa和aes加解密