Java-AES加解密

代码实现

package com.donate.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * AES加解密工具。
 * @author yanghaitao
 *
 */
public class AesUtils {
    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String BASE64STRING = "12345678123456783";
    private static final byte[] KEY = Base64.encodeBase64(BASE64STRING.getBytes());
    
    /**
     * encrypt : 加密数据
     */
    public static String encrypt(String context) throws Exception {
        return Base64.encodeBase64String(encrypt(context.getBytes(), KEY));
    }
    
    /**
     * decrypt : 解密数据
     */
    public static String decrypt(String context) throws Exception {
        return new String(decrypt(Base64.decodeBase64(context), KEY));
    }
    
    /**
     * encrypt : 加密数据
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 还原密钥
        SecretKey k = new SecretKeySpec(key, KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化,设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, k);
        // 执行操作
        return cipher.doFinal(data);
    }
    
    /**
     * decrypt : 解密数据
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 欢迎密钥
        SecretKey k = new SecretKeySpec(key, KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化,设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, k);
        // 执行操作
        return cipher.doFinal(data);
    }
}

代码示例

String context = "12345678!qaz@WSX";
String data1 = AesUtils.encrypt(context);
System.err.println(data1);

String data2 = AesUtils.decrypt(data1);
System.err.println(data2);
上一篇:HTTP与HTTPS


下一篇:零起点入门系列教程⑥:如何用钉钉宜搭制定企业疫情防控数字化管理方案