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等压缩类文件之后进行解密会产生头信息被损坏的现象,望各位大神提供下解决思路。