private static final String key = "aesEncryptionKey";
private static final String initVector = "encryptionIntVec";
/*
* Getting a 128 bit key and iv for encryption
*/
public static InputStream encriptFile(InputStream inputFile) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
byte[] nonEncryptedByteArray = IOUtils.toByteArray(inputFile);
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec secretkey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); //Cipher instance using AES encryption algorithm
cipher.init(Cipher.ENCRYPT_MODE, secretkey, iv);
byte[] encryptedByteArray = cipher.doFinal(nonEncryptedByteArray);
/*
* Used the cipher library to encrypt the stream to a byte array
*/
InputStream encryptedInputStream = new ByteArrayInputStream(encryptedByteArray);
/*
* Back to streams, but this time encrypted
*/
return encryptedInputStream;
}
public static InputStream decriptFile(InputStream inputFile) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] encrytToDecryptByteArray = IOUtils.toByteArray(inputFile);
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec secretkey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretkey, iv);
byte[] decryptedByteArray = cipher.doFinal(encrytToDecryptByteArray);
/*
* dencrypted the encrypted data
*/
InputStream decryptedInputStream = new ByteArrayInputStream(decryptedByteArray);
return decryptedInputStream;
}
主要方法如下:
File file = new File("test.txt");
InputStream is = new FileInputStream(file);
InputStream eis = encriptFile(is);
StringWriter writer = new StringWriter();
IOUtils.copy(eis, writer, "UTF-8");
String theString = writer.toString();
System.out.print(theString);