Java:AES加密解密

目录

  • [1 加密解密源代码](#1 加密解密源代码)
  • [2 随机生成16位密钥](#2 随机生成16位密钥)

1 加密解密源代码

java 复制代码
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class Test {
    public static void main(String[] args) throws Exception {
        String source = "这是一段明文";
        String encrypted = encrypt(source);
        String decrypted = decrypt(encrypted);
        System.out.println("原文: " + source);
        System.out.println("加密后: " + encrypted);
        System.out.println("解密后: " + decrypted);
    }

    // AES密钥
    private static final String KEY = "8t2pchk3Rg0-nmiQ";
    // 初始化向量,AES 为16bytes. DES 为8bytes
    private static final String IV = "N9LnJ3E2y5P*ZssP";
    // 加密算法/模式/填充方式
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    // 加密
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // 解密
    public static String decrypt(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decoded = Base64.getDecoder().decode(encryptedData);
        byte[] original = cipher.doFinal(decoded);
        return new String(original, "UTF-8");
    }
}

2 随机生成16位密钥

java 复制代码
package org.ming.utils;

import java.security.SecureRandom;

public class PasswordGenerator {
    private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";

    private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final String DIGITS = "0123456789";

    private static final String SPECIAL_CHARACTERS = "!@#$%^&*_=+-/";

    private static final String ALL_CHARACTERS = LOWERCASE_CHARACTERS + UPPERCASE_CHARACTERS + DIGITS;


    public static void main(String[] args) {
        // 一次性生成的密码数量
        int passwordCount = 10;
        for (int i = 0; i < passwordCount; i++) {
            // 打印每次生成的密码
            System.out.println(generatePassword());
        }
    }

    /**
     * @Description: 生成含有指定小写字母、大写字母和数字字符以及特殊字符数量和固定长度的随机密码
     * @author EXT.AZHANG
     * @return String
     * @date 2024-08-12
     */
    private static String generatePassword() {

        int passwordLength = 16; // 密码长度
        // 确保至少包含一个小写字母、一个大写字母和一个数字字符以及一个特殊字符 把数量都设置为1
        int lowerCaseCount = 1; // 小写字母数量
        int upperCaseCount = 1; // 大写字母数量
        int numberCount = 1; // 数字数量
        int specialCount =1; // 特殊字符数量
        StringBuilder randomString = new StringBuilder(passwordLength);
        SecureRandom random = new SecureRandom();
        // 随机生成大写字母部分
        for (int i = 0; i < lowerCaseCount; i++) {
            int lowerCaseIndex = random.nextInt(LOWERCASE_CHARACTERS.length());
            randomString.append(LOWERCASE_CHARACTERS.charAt(lowerCaseIndex));
        }
        // 随机生成小写字母部分
        for (int i = 0; i < upperCaseCount; i++) {
            int upperCaseIndex = random.nextInt(UPPERCASE_CHARACTERS.length());
            randomString.append(UPPERCASE_CHARACTERS.charAt(upperCaseIndex));
        }
        // 随机生成数字部分
        for (int i = 0; i < numberCount; i++) {
            int digitsIndex = random.nextInt(DIGITS.length());
            randomString.append(DIGITS.charAt(digitsIndex));
        }
        // 随机生成特殊字符部分
        for (int i = 0; i < specialCount; i++) {
            int specialIndex = random.nextInt(SPECIAL_CHARACTERS.length());
            randomString.append(SPECIAL_CHARACTERS.charAt(specialIndex));
        }
        // 生成剩余的字符
        for (int i = lowerCaseCount+upperCaseCount+numberCount+specialCount; i < passwordLength; i++) {
            // 在所有字符里面取剩下的字符
            randomString.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
        }
        // 洗牌字符,使其顺序随机
        return shuffleString(randomString.toString());
    }

    /**
     *
     * @Description: 函数用于洗牌字符串中的字符
     * @author EXT.AZHANG
     * @param input
     * @return String
     * @date 2024-08-12
     */
    private static String shuffleString(String input) {
        SecureRandom random = new SecureRandom();
        char[] characters = input.toCharArray();
        for (int i = characters.length - 1; i > 0; i--) {
            int randomIndex = random.nextInt(i + 1);
            char temp = characters[i];
            characters[i] = characters[randomIndex];
            characters[randomIndex] = temp;
        }
        return new String(characters);
    }
}
相关推荐
上单带刀不带妹几秒前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
im_AMBER21 分钟前
学习日志05 python
python·学习
都叫我大帅哥21 分钟前
🌊 Redis Stream深度探险:从秒杀系统到面试通关
java·redis
都叫我大帅哥22 分钟前
Redis持久化全解析:从健忘症患者到记忆大师的逆袭
java·redis
大虫小呓26 分钟前
Python 处理 Excel 数据 pandas 和 openpyxl 哪家强?
python·pandas
哪 吒38 分钟前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
程序猿阿越41 分钟前
Kafka源码(一)Controller选举与创建Topic
java·后端·源码
-凌凌漆-41 分钟前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼41 分钟前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin