mail@pastecode.io avatar
6 months ago
2.1 kB
Certainly! Here's a simple example of a Java program that encrypts a file using AES-256 in CBC mode. Make sure to handle exceptions and manage resources appropriately in a production environment.

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;

public class FileEncryptor {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    public static void main(String[] args) {
        try {
            // Replace 'yourKey' and 'yourInitializationVector' with your actual key and IV
            String key = "yourKey";
            String iv = "yourInitializationVector";

            encryptFile("input.txt", "encryptedOutput.enc", key, iv);
            System.out.println("Encryption completed successfully.");

        } catch (Exception e) {

    public static void encryptFile(String inputFile, String outputFile, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

        try (FileInputStream inputStream = new FileInputStream(inputFile);
             FileOutputStream outputStream = new FileOutputStream(outputFile);
             CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                cipherOutputStream.write(buffer, 0, bytesRead);


Remember to replace the placeholder values for 'yourKey' and 'yourInitializationVector' with your actual key and initialization vector. Additionally, handle exceptions and errors appropriately for a robust implementation.
Leave a Comment