AES对称加密

本文介绍对称加密的基本概念及其在Java中的具体实现方式,包括AES算法的使用、密钥生成及加密解密过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对称加密就是加密解密同时使用一个密钥

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;

public class SymmetricEncoder {
    /**
     * 加密
     *
     * @param content 加密文本
     * @return 加密后的文本
     * @throws Exception
     */
    private static String aesEncode(String content) throws Exception {
        // 获取 加密器
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
        //加密内容的字节数组,指定字符集utf-8,否则解密时乱码
        byte[] contentBytes = content.getBytes("utf-8");
        //加密
        byte[] bytes = cipher.doFinal(contentBytes);
        return new String(new BASE64Encoder().encode(bytes));
    }

    /**
     * 解密
     *
     * @param content 解密的文本
     * @return 解密后的文本
     * @throws Exception
     */
    private static String aesDncode(String content) throws Exception {
        // 获取 解密器
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
        // 将加密并编码后的内容解码成字节数组
        byte[] bytes = new BASE64Decoder().decodeBuffer(content);
        // 解密
        byte[] decodeByte = cipher.doFinal(bytes);
        // 指定加密时的字符集
        return new String(decodeByte, "utf-8");

    }

    /**
     * 获取密码器
     * <p>
     * 对称加密 所以加密和解密使用同一个规则生成同一个密钥生成器(公钥 = 私钥)
     * 使用同一个密钥生成器生成同一个密码器,即对称加密
     *
     * @param mode 加密(Cipher.Encrypt_mode)或解密(Cipher.Decrypt_mode)
     * @return 密码器
     * @throws Exception
     */
    private static Cipher getCipher(int mode) throws Exception {
        // 密钥生成器,指定为AES算法
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        // 根据规则初始化密钥生成器, 1234-> 自定义的字符串
        keyGenerator.init(128, new SecureRandom(new String("1234").getBytes()));
        // 产生对称密钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 根据字节数组生成AES密钥
        Key key = new SecretKeySpec(secretKey.getEncoded(), "AES");
        // 根据指定算法AES自成密码器
        Cipher cipher = Cipher.getInstance("AES");
        // 初始化密码器
        // 第一个参数为加密(Cipher.Encrypt_mode)或解密(Cipher.Decrypt_mode)
        // 第二个参数为使用的KEY
        cipher.init(mode, key);
        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String e = aesEncode("床前明月光,疑是地上霜,举头望明月,低头思故乡");
        System.out.println(e);
        String d = aesDncode(e);
        System.out.println(d);
    }

}

控制台输出:

I/xtcl4/KraxXJ9GJOIVBmx6hQcpMdSfVVYV4ZidFPs9ylM7zVdED5HYK+a5aektYy4TCJvb321i
Ga0pXytI3w==
床前明月光,疑是地上霜,举头望明月,低头思故乡

转载于:https://my.oschina.net/u/3886184/blog/1929494

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值