Article directory
- File encryption and decryption
-
- encrypt documents
- File decryption
- Folder encryption and decryption
-
- Encrypt files
- Decrypt files
File encryption and decryption
Encryption and decryption using AES algorithm
AEC is the abbreviation of Advanced Encryption Standard. It is a symmetric key encryption algorithm commonly used for data encryption and privacy protection.
package com.sin.utils; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * @createTime 2023/10/18 11:24 * @createAuthor SIN * @use file encryption and decryption */ public class DocumentEncryptionUtil {<!-- --> // File encryption method private static final String ALGORITHM = "AES"; /** * encrypt documents * @param secretKey file encryption key * @param sourceFilePath needs to encrypt the file address * @param destinationFilePath encrypted file address */ public static void encryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {<!-- --> // Generate a secret key using the key string SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM); // Get an instance of the AES encryption algorithm Cipher cipher = Cipher.getInstance(ALGORITHM); // Initialize the cipher cipher using the secret key, set to encryption mode cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); // Get the source file path Path sourcePath = Paths.get(sourceFilePath); // Get the target encrypted file path Path destinationPath = Paths.get(destinationFilePath); //Create an input stream and read the source file try (InputStream inputStream = Files.newInputStream(sourcePath); //Create an output stream and write the encrypted file OutputStream outputStream = Files.newOutputStream(destinationPath); // Create a cipher output stream, connect to the output stream, and encrypt using the password cipher CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {<!-- --> // buffer size byte[] buffer = new byte[4096]; int bytesRead; //Read the source file content into the buffer while ((bytesRead = inputStream.read(buffer)) != -1) {<!-- --> //Write the encrypted data to the encrypted file cipherOutputStream.write(buffer, 0, bytesRead); } } } /** *File decryption * @param secretKey file decryption key * @param sourceFilePath The file address to be decrypted * @param destinationFilePath decrypted file address */ public static void decryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {<!-- --> SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM); // Generate a secret key using the key string Cipher cipher = Cipher.getInstance(ALGORITHM); // Get an instance of the AES encryption algorithm cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); // Initialize the password cipher using the secret key and set it to decryption mode Path sourcePath = Paths.get(sourceFilePath); // Get the source encrypted file path Path destinationPath = Paths.get(destinationFilePath); // Get the target decrypted file path try (InputStream inputStream = Files.newInputStream(sourcePath); // Create an input stream and read the encrypted file OutputStream outputStream = Files.newOutputStream(destinationPath); // Create an output stream and write the decrypted file CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher)) {<!-- --> // Create a cipher input stream, connect to the input stream, and use the password cipher to decrypt byte[] buffer = new byte[4096]; // buffer size int bytesRead; while ((bytesRead = cipherInputStream.read(buffer)) != -1) {<!-- --> // Read the contents of the encrypted file into the buffer outputStream.write(buffer, 0, bytesRead); //Write the decrypted data to the decrypted file } } } }
File encryption
The target file is the content
package com.sin.utils.test; import com.sin.utils.DocumentEncryptionUtil; import org.junit.Test; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * @createTime 2023/10/18 11:28 * @createAuthor SIN * @use */ public class DocumentEncryptionUtilTest {<!-- --> /** * encrypt documents */ @Test public void encryptFileTest(){<!-- --> try {<!-- --> DocumentEncryptionUtil.encryptFile("SIN-80238023-@@@","D:/FileEncryptionUtil.txt","D:/Demo/FileEncryptionUtil.txt"); } catch (NoSuchAlgorithmException e) {<!-- --> throw new RuntimeException(e); } catch (NoSuchPaddingException e) {<!-- --> throw new RuntimeException(e); } catch (InvalidKeyException e) {<!-- --> throw new RuntimeException(e); } catch (IOException e) {<!-- --> throw new RuntimeException(e); } }
encrypted file
File decryption
/** *File decryption */ @Test public void decryptFileTest(){<!-- --> try {<!-- --> DocumentEncryptionUtil.decryptFile("SIN-80238023-@@@","D:/Demo/FileEncryptionUtil.txt","D:/Demo/FileEncryptionUtil1.txt"); } catch (NoSuchAlgorithmException e) {<!-- --> throw new RuntimeException(e); } catch (NoSuchPaddingException e) {<!-- --> throw new RuntimeException(e); } catch (InvalidKeyException e) {<!-- --> throw new RuntimeException(e); } catch (IOException e) {<!-- --> throw new RuntimeException(e); } }
Decrypted file
Folder encryption and decryption
package com.sin.utils; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * @createTime 2023/10/19 9:20 * @createAuthor SIN * @use folder encryption and decryption */ public class FileEncryptionUtil {<!-- --> //AES is the abbreviation of Advanced Encryption Standard. It is a symmetric key encryption algorithm commonly used for data encryption and privacy protection. private static final String ALGORITHM = "AES"; /** * Remove file name extension * @param fileName the file to be operated on * @return */ private static String removeExtension(String fileName) {<!-- --> // Find the last point of the file int dotIndex = fileName.lastIndexOf("."); // Ensure that the points are not the first and last characters of the file name if (dotIndex > 0 & amp; & amp; dotIndex < fileName.length() - 1) {<!-- --> // Return a valid extension return fileName.substring(0, dotIndex); } //Return to source file return fileName; } /** * Folder encryption * @param secretKey folder encryption key * @param sourceFilePath The folder that needs to be encrypted * @param destinationFilePath encrypted folder address */ public static void encryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {<!-- --> // Generate a secret key using the key string SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM); // Get an instance of the AES encryption algorithm Cipher cipher = Cipher.getInstance(ALGORITHM); // Initialize the cipher cipher using the secret key, set to encryption mode cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); // Get the source file or folder path Path sourcePath = Paths.get(sourceFilePath); // Get the target encrypted file or folder path Path destinationPath = Paths.get(destinationFilePath); if (Files.isDirectory(sourcePath) & amp; & amp; !Files.exists(destinationPath)) {<!-- --> //Create target folder Files.createDirectories(destinationPath); // Traverse the source folder try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourcePath)) {<!-- --> for (Path filePath : directoryStream) {<!-- --> //Encrypted file name String encryptedFileName = filePath.getFileName().toString() + ".enc"; //Encrypted file path String encryptedFilePath = destinationPath.resolve(encryptedFileName).toString(); // Call the encryption method recursively to process sub-files or sub-folders encryptFile(secretKey,filePath.toString(), encryptedFilePath); } } } else if (Files.isRegularFile(sourcePath)) {<!-- --> //Create an input stream and read the source file try (InputStream inputStream = Files.newInputStream(sourcePath); //Create an output stream and write the encrypted file OutputStream outputStream = Files.newOutputStream(destinationPath); //Create a cipher output stream, connect to the output stream, and encrypt using the password cipher CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {<!-- --> // buffer size byte[] buffer = new byte[4096]; int bytesRead; //Read the source file content into the buffer while ((bytesRead = inputStream.read(buffer)) != -1) {<!-- --> //Write the encrypted data to the encrypted file cipherOutputStream.write(buffer, 0, bytesRead); } } } } /** * * @param secretKey folder decryption key * @param sourceFilePath The folder to be decrypted * @param destinationFilePath decrypted folder address */ public static void decryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {<!-- --> SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM); // Generate a secret key using the key string Cipher cipher = Cipher.getInstance(ALGORITHM); // Get an instance of the AES encryption algorithm cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); // Initialize the password cipher using the secret key and set it to decryption mode Path sourcePath = Paths.get(sourceFilePath); // Get the source encrypted file or folder path Path destinationPath = Paths.get(destinationFilePath); // Get the target decrypted file or folder path if (Files.isDirectory(sourcePath) & amp; & amp; !Files.exists(destinationPath)) {<!-- --> Files.createDirectories(destinationPath); // Create destination folder try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourcePath)) {<!-- --> // Traverse the source folder for (Path filePath : directoryStream) {<!-- --> String decryptedFileName = removeExtension(filePath.getFileName().toString()); // Remove the extension of the file name String decryptedFilePath = destinationPath.resolve(decryptedFileName).toString(); // Decrypted file path decryptFile(secretKey,filePath.toString(), decryptedFilePath); // Recursively call the decryption method to process sub-files or sub-folders } } } else if (Files.isRegularFile(sourcePath)) {<!-- --> try (InputStream inputStream = Files.newInputStream(sourcePath); // Create an input stream and read the encrypted file OutputStream outputStream = Files.newOutputStream(destinationPath); // Create an output stream and write the decrypted file CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher)) {<!-- --> // Create a cipher input stream, connect to the input stream, and use the password cipher to decrypt byte[] buffer = new byte[4096]; // buffer size int bytesRead; while ((bytesRead = cipherInputStream.read(buffer)) != -1) {<!-- --> // Read the contents of the encrypted file into the buffer outputStream.write(buffer, 0, bytesRead); //Write the decrypted data to the decrypted file } } } } }
Files that need to be encrypted
Encrypted files
package com.sin.utils.test; import com.sin.utils.FileEncryptionUtil; import org.junit.Test; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * @createTime 2023/10/19 9:32 * @createAuthor SIN * @use test folder encryption and decryption */ public class FileEncryptionUtilTest {<!-- --> /** * Encrypted files */ @Test public void encryptFileTest(){<!-- --> try {<!-- --> FileEncryptionUtil.encryptFile("sin-80238023-@@@","D:/Demo","D:/Demo1"); } catch (NoSuchAlgorithmException e) {<!-- --> throw new RuntimeException(e); } catch (NoSuchPaddingException e) {<!-- --> throw new RuntimeException(e); } catch (InvalidKeyException e) {<!-- --> throw new RuntimeException(e); } catch (IOException e) {<!-- --> throw new RuntimeException(e); } }
encrypted file
Decrypt files
/** * Decrypt files */ @Test public void decryptFile(){<!-- --> try {<!-- --> FileEncryptionUtil.decryptFile("sin-80238023-@@@","D:/Demo1","D:/Demo2"); } catch (NoSuchAlgorithmException e) {<!-- --> throw new RuntimeException(e); } catch (NoSuchPaddingException e) {<!-- --> throw new RuntimeException(e); } catch (InvalidKeyException e) {<!-- --> throw new RuntimeException(e); } catch (IOException e) {<!-- --> throw new RuntimeException(e); } }
Decrypted file