AES加密文件:
/**
* 加密文件
* @param sourceFile 源文件(未加密文件)
* @param tragetFile 目标文件名(加密后文件)
* @publicKeys RSA公钥
*/
public static boolean encodeFile(File sourceFile, String tragetFile, String publicKeys) {
OutputStream out = null;
InputStream in = null;
try {
if (!sourceFile.exists()) {
return false;
}
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(KEY_SIZE);
/**
* 随机生成AES密钥
*/
SecretKey key = keyGen.generateKey();
Key publicKey = RSAUtils.getPublicKey(publicKeys);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.WRAP_MODE, publicKey);
/**
* 使用RSA公钥加密AES密钥
*/
byte[] wrappedKey = cipher.wrap(key);
out = new FileOutputStream(tragetFile);
/**
* 将加密后的AES密钥写入加密文件头部
*/
out.write(wrappedKey, 0, wrappedKey.length);
in = new FileInputStream(sourceFile);
/**
* AES加密文件
*/
copyStream(key, in, out, true);
return true;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return false;
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return false;
} catch (InvalidKeyException e) {
e.printStackTrace();
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
return false;
} catch (BadPaddingException e) {
e.printStackTrace();
return false;
} finally {
return freeSource(out, in);
}
}
```