我的执着 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
    关注
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?