教学服务系统

 找回密码
 立即注册
搜索
查看: 603|回复: 0

信息计算2019级1班17号刘帆杰

[复制链接]

9

主题

16

帖子

117

积分

注册会员

Rank: 2

积分
117
发表于 2022-4-5 18:05:18 | 显示全部楼层 |阅读模式
本帖最后由 刘帆杰 于 2022-4-7 15:10 编辑

import org.apache.commons.io.FileUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.Key;
import java.util.Base64;


public class AES {
    public static final String KEY_ALGORITHM = "AES";//加密算法
    public static final String CIPHER_ALGORITHM ="AES/ECB/PKCS5Padding";//加密/解密算法/工作模式/填充方法

    public static void main(String[] args) {
        File srcFile=new File("src/main/java/com/example/test/a.docx");   //初始文件
        File encFile=new File("src/main/java/com/example/test/b.docx");   //加密文件
        File decFile=new File("src/main/java/com/example/test/c.docx");   //解密文件
        try {
            OutputStream fos = new FileOutputStream(encFile);
            OutputStream fos2 = new FileOutputStream(decFile);

            byte[] a = FileUtils.readFileToByteArray(srcFile);  //读取源文件

            byte[] b=initKey();     //生成密钥

            byte[] c=encrept(a,b);  //AES加密

            fos.write(Base64.getEncoder().encode(c));   //Base64编码

            byte[] d=FileUtils.readFileToByteArray(encFile);    //读取加密文件

            byte[] e=decrept(Base64.getDecoder().decode(d),b );     //Base64解码再用密钥解密

            fos2.write(e);  //将译文输出
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //加密
    public static byte[] encrept(byte[] data,byte[] key) throws Exception{
        Key k=new SecretKeySpec(key,KEY_ALGORITHM);
        Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,k); //设置加密模式
        return cipher.doFinal(data);
    }

    //解密
    public static byte[] decrept(byte[] data,byte[] key) throws Exception{
        Key k=new SecretKeySpec(key,KEY_ALGORITHM);
        Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,k); //设置解密模式
        return cipher.doFinal(data);
    }

    //生成密钥
    public static byte[] initKey() throws Exception{
        KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(256);   //密钥可初始化为128256
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }
}

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

教学服务系统

GMT+8, 2025-4-30 08:16 , Processed in 0.021243 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表