我的执着
2017-07-16 14:48Java AES-256加密文件之后解密文件,文件被损坏
20public 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条回答
为你推荐
- AES-256-CBC加密在golang和node / php之间不匹配
- encryption
- aes
- php
- node.js
- 1个回答
- 如何在Go中加密大型文件/字节流?
- aes
- encryption
- 2个回答
- AES-128-CTR加密在PHP(openssl_encrypt)和Node.js(加密)上给出不同的结果
- aes
- encryption
- php
- node.js
- 1个回答
- AES-256-CBC Mcrypt-PHP解密和Crypto-JS加密
- javascript
- aes
- encryption
- php
- 1个回答
- PHP AES加密JAVA到PHP - openssl_encrypt
- encryption
- php
- 1个回答