Java中AES算法(对称加密)

该博客展示了两种使用Java实现AES加密和解密的方法。第一种方法通过KeyGenerator生成密钥,并使用Cipher进行加解密操作。第二种方法使用了SecretKeySpec和Base64编码。代码详细注释说明了每一步操作。
摘要由CSDN通过智能技术生成

 话不多说上代码(思路大体一致):

第一种:

package *;

import com.*.exception.exceptions.BusinessException;

import javax.crypto.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 数据加密工具类
 *
 * @author wblongkui
 * @version 1.0
 * @since 2021-03-17
 */
public class EncryptionUtil {
    static final String ALGORITHM = "AES";

    /**
     * 生成密钥,密钥是SecretKey类型的对象
     *
     * @return SecretKey
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     */
    public static SecretKey generateKey(String password) throws NoSuchAlgorithmException {
        // 创建AES的Key生产者
        KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
        // 利用用户密码作为随机数初始化出128位的key生产者
        secretGenerator.init(128, new SecureRandom(password.getBytes()));
        return secretGenerator.generateKey();
    }

    /**
     * 加密
     *
     * @param content   明文
     * @param secretKey 密钥
     * @return byte[]
     */
    public static byte[] encrypt(String content, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return aes(content.getBytes(StandardCharsets.UTF_8), Cipher.ENCRYPT_MODE, secretKey);
    }

    /**
     * 解密
     *
     * @param contentArray 密文
     * @param secretKey    密钥
     * @return 明文字符串
     */
    public static String decrypt(byte[] contentArray, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey);
        return new String(result, StandardCharsets.UTF_8);
    }

    private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, secretKey);
        return cipher.doFinal(contentArray);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf byte[]
     * @return String
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr String
     * @return byte[]
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密数据
     * @param password 密钥
     * @param data 明文数据
     * @return 加密数据
     */
    public static String encryptionData(String password, String data){
        try {
            SecretKey secretKey = generateKey(password);
            byte[] encryptResult = encrypt(data, secretKey);
            return parseByte2HexStr(encryptResult);

        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            throw BusinessException.build("加密数据出现异常");
        }
    }

    /**
     * 解密数据
     * @param password 密钥
     * @param data 密文数据
     * @return 明文数据
     */
    public static String decryptData(String password, String data){
        try {
            SecretKey secretKey = generateKey(password);
            byte[] bytes = parseHexStr2Byte(data);
            return decrypt(bytes, secretKey);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            throw BusinessException.build("解密数据出现异常");
        }
    }

    public static void main(String[] args) {
        String content = "this is AES";
        System.out.println("原始数据为: " + content);
        String password = "asdfzxcq";
        String parseByte2HexStr = encryptionData(password, content);
        System.out.println("加密后的结果为:" + parseByte2HexStr);
        System.out.println("加密后的结果长度为:" + parseByte2HexStr.length());


        String decryptResult = decryptData(password, parseByte2HexStr);
        System.out.println("解密后的结果为:" + decryptResult);
        System.out.println("原始数据和解密后的数据对比: " + content.equals(decryptResult));

    }

}

 第二种:

package *;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Aes128Util {
    public Aes128Util() {
    }

    public static String encrypt(String explainMessage, String key) throws Exception {
        if (!StringUtil.isEmpty(explainMessage) && !StringUtil.isEmpty(key) && key.length() == 16) {
            byte[] raw = key.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(1, skeySpec);
            byte[] encrypted = cipher.doFinal(explainMessage.getBytes("UTF-8"));
            return Base64.encodeBase64String(encrypted);
        } else {
            return null;
        }
    }

    public static String decrypt(String encryptMessage, String key) throws Exception {
        if (!StringUtil.isEmpty(encryptMessage) && !StringUtil.isEmpty(key) && key.length() == 16) {
            byte[] raw = key.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, skeySpec);
            byte[] encrypted1 = (new Base64()).decode(encryptMessage);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "UTF-8");
        } else {
            return null;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值