我的执着 2017-07-16 14:48 采纳率: 0%
浏览 2059
已结题

Java AES-256加密文件之后解密文件,文件被损坏

public static Cipher initAESCipher(String password, int cipherMode) {
// 创建Key gen
KeyGenerator keyGenerator = null;
Cipher cipher = null;
try {
keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256, new SecureRandom(password.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
byte[] codeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(codeFormat, "AES");
cipher = Cipher.getInstance("AES/ECB/PKCS7Padding","BC");
// 初始化
cipher.init(cipherMode, key);
return cipher;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); // To change body of catch statement use File |
} catch (NoSuchPaddingException e) {
e.printStackTrace(); // To change body of catch statement use File |
} catch (InvalidKeyException e) {
e.printStackTrace(); // To change body of catch statement use File |
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


public static void encrypt(File source, File target, String password) throws Exception {
InputStream input = new FileInputStream(source);
OutputStream ouput = new FileOutputStream(target);
logger.debug("开始写入加密文件");
long start = System.currentTimeMillis();
CipherInputStream cipherInputStream = (CipherInputStream) encrypt(input, password);
IOUtils.copy(cipherInputStream,ouput );
cipherInputStream.close();
input.close();
ouput.close();
logger.debug("完成文件加密,耗时:" + (System.currentTimeMillis() - start));
}


public static InputStream encrypt(InputStream input, String password) {
logger.debug("开始加密文件流");
long start = System.currentTimeMillis();
Cipher cipher = initAESCipher(password, Cipher.ENCRYPT_MODE);
logger.debug("生成密钥耗时:" + (System.currentTimeMillis() - start));
Assert.notNull(cipher);
// 以加密流写入文件
CipherInputStream cipherInputStream = new CipherInputStream(input, cipher);
logger.debug("完成加密文件流,耗时:" + (System.currentTimeMillis() - start));
return cipherInputStream;
}


目前发现加密DOCX,PPTX,ZIP等压缩类文件之后进行解密会产生头信息被损坏的现象,望各位大神提供下解决思路。

  • 写回答

1条回答

  • zqbnqsdsmd 2018-07-30 16:09
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。