java编写操作 对称加密 AES 加密解密

package com.fingerchar.core.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {

    private static final String ALGORITHM_NAME = "AES";//加密因子,可根据您的需要自定义

    private static final String DEFAULT_ENCRYPT_RULE = "AES/CBC/PKCS5Padding";
    private static final String RANDOM_KEY_ALGORITHM = "SHA1PRNG";
    private static final String RANDOM_KEY_ALGORITHM_PROVIDER = "SUN";

    //密钥的存放位置
    private static  String keyUrl = "/Users/langjunnan/Desktop/aeskey/aes1.key";

    /**
     * 生成密钥
     * @return
     * @throws Exception
     */
    private SecretKey geneKey() throws Exception {
        //获取一个密钥生成器实例
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_NAME);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // random.setSeed("123456".getBytes());//设置加密用的种子,密钥,这个可不操作,固定了的话每次出来的密钥时一样的
        keyGenerator.init(random);
        SecretKey secretKey = keyGenerator.generateKey();
        //把上面的密钥存起来
        Path keyPath = Paths.get(keyUrl);
        Files.write(keyPath, secretKey.getEncoded());
        return secretKey;
    }

    /**
     * AES加密
     * @param content 待加密的内容,为空时为回空
     * @return 加密后的base64格式的结果,出现异常时返回null
     */
    public  String encrypt(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        try {
            Path keyPath = Paths.get(keyUrl);
            SecretKey secretKey =  this.readKey(keyPath);
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            String result = new String(Base64.getEncoder().encodeToString(encrypted));
            return  result;
        } catch (Exception e) {
            e.printStackTrace();
             return null;
        }
    }


    /**
     * 解密
     * @param encrypted 加密后的base64格式的密文
     * @return 解密后的原文,出现异常时返回null
     */
    public  String decrypt(String encrypted) {
        if (StringUtils.isEmpty(encrypted)) {
            return null;
        }
        try {
//            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_NAME);
//            SecureRandom secureRandom = SecureRandom.getInstance(RANDOM_KEY_ALGORITHM, RANDOM_KEY_ALGORITHM_PROVIDER);
//            secureRandom.setSeed(DEFAULT_ENCRYPT_RULE.getBytes());
//            keyGenerator.init(128, secureRandom);
//            SecretKey originalKey = keyGenerator.generateKey();
            // SecretKey secretKey = new SecretKeySpec(originalKey.getEncoded(), ALGORITHM_NAME);
            Path keyPath = Paths.get(keyUrl);
            SecretKey secretKey = this.readKey(keyPath);
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encrypted));
            return new String(decrypted, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
         AESUtil aesUtil1=new AESUtil();
//        String s=aesUtil1.encrypt("XXXXXXXXXXGGGGGGGGGGffffffffff4444444444333333333322222222222111111111199999999990000000000888888888877777777776666666666555555555544444444443333333333");
//        System.out.println(s);
//        String r= aesUtil1.decrypt(s);
//        System.out.println(r);
        try{
            // 生成密钥 aesUtil1.geneKey();
            String data="Connected to the target VM, address: '127.0.0.1:59471', transport: 'socket'aaaaaaaaaadsn1273w762183292198273t27139214898288282222288888888888833333333333333333333333博客,仅音译,英文名为Blogger,为Web Log的混成词。它的正式名称为网络日记;又音译为部落格或部落阁等,是使用特定的软件,在网络上出版、发表和张贴个人文章的人,或者是一种通常由个人管理、不定期张贴新的文章的网站。博客上的文章通常以网页形式出现,并根据张贴时间,以倒序排列。通常具备RSS订阅功能。博客是继MSN、BBS、ICQ之后出现的第4种网络交流方式,现已受到大家的欢迎,是网络时代的个人“读者文摘”,是以超级链接为入口的网络日记,它代表着新的生活、工作和学习方式。许多博客专注在特定的课题上提供评论或新闻,其他则被作为个人性的日记。一个典型的博客结合了文字、图像、其他博客或网站的链接及其它与主题相关的媒体,能够让读者以互动的方式留下意见,是许多博客的重要要素。大部分的博客内容以文字为主,但仍有一些博客专注在艺术、摄影、视频、音乐、播客等各种主题。博客是社会媒体网络的一部分。比较著名的有新浪等博客";
            String result=aesUtil1.encrypt(data);
            System.out.println("加密后的串是 = " +result);
            String result1=    aesUtil1.decrypt(result);
            System.out.println("解密铭文是=:"+result1);

        }catch (Exception e){
            e.printStackTrace();;
        }





    }
    /**
     * 读取存储的密钥
     * @param keyPath
     * @return
     * @throws Exception
     */
    private SecretKey readKey(Path keyPath) throws Exception {
        //读取存起来的密钥
        byte[] keyBytes = Files.readAllBytes(keyPath);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
        return keySpec;
    }

}

  

posted @ 2022-07-20 13:48  郎小乐  阅读(138)  评论(0编辑  收藏  举报