How to encrypt file streams in Java?
Java has the ability to encrypt file streams using cryptographic streams. Cryptographic streams are a special type of input/output stream provided by the Java IO library that can encrypt and decrypt the underlying file stream. Below is a simple example code demonstrating how to encrypt files using cryptographic streams.
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class FileEncryption {
public static void main(String[] args) {
String sourceFile = "source.txt";
String encryptedFile = "encrypted.txt";
String decryptedFile = "decrypted.txt";
String key = "1234567890abcdef"; // 密钥,16位字符
try {
encrypt(sourceFile, encryptedFile, key);
System.out.println("文件加密成功!");
decrypt(encryptedFile, decryptedFile, key);
System.out.println("文件解密成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void encrypt(String sourceFile, String encryptedFile, String key) throws Exception {
File inputFile = new File(sourceFile);
File outputFile = new File(encryptedFile);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
cipherOutputStream.write(buffer, 0, bytesRead);
}
cipherOutputStream.close();
inputStream.close();
}
public static void decrypt(String encryptedFile, String decryptedFile, String key) throws Exception {
File inputFile = new File(encryptedFile);
File outputFile = new File(decryptedFile);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = cipherInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
cipherInputStream.close();
}
}
In the above example, we used the AES algorithm to encrypt and decrypt files. It’s important to note that the AES algorithm requires a 16-bit key, so we used a 16-bit string as the key in our code. In real-world applications, you may need to use a more secure method for generating keys.
This is just a simple example, in reality, you may need to deal with more exceptional cases and use a more secure encryption method.