ITPub博客

首页 > 应用开发 > Java > java实现文本文件进行加密和解密

java实现文本文件进行加密和解密

原创 Java 作者:mingtian66 时间:2024-09-20 12:56:38 0 删除 编辑

下面是一个简单的 Java 示例,演示如何对文本文件进行加密和解密。我们将使用 AES(高级加密标准)进行加密和解密。
1. 添加依赖

如果你使用 Maven,可以在 pom.xml 中添加以下依赖:

xml

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

2. Java 加密和解密示例

下面是完整的 Java 代码示例,包括文件的加密和解密功能。

java

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileEncryptDecrypt {

    private static final String ALGORITHM = "AES";

    public static void main(String[] args) throws Exception {
        String key = "1234567890123456"; // 16 字节的密钥
        File originalFile = new File("example.txt");
        File encryptedFile = new File("encrypted_example.txt");
        File decryptedFile = new File("decrypted_example.txt");

        // 加密
        encrypt(key, originalFile, encryptedFile);
        System.out.println("文件加密成功!");

        // 解密
        decrypt(key, encryptedFile, decryptedFile);
        System.out.println("文件解密成功!");
    }

    public static void encrypt(String key, File inputFile, File outputFile) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        try (FileInputStream inputStream = new FileInputStream(inputFile);
             FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            byte[] inputBytes = new byte[64];
            int bytesRead;

            while ((bytesRead = inputStream.read(inputBytes)) != -1) {
                byte[] outputBytes = cipher.update(inputBytes, 0, bytesRead);
                if (outputBytes != null) {
                    outputStream.write(outputBytes);
                }
            }
            byte[] outputBytes = cipher.doFinal();
            if (outputBytes != null) {
                outputStream.write(outputBytes);
            }
        }
    }

    public static void decrypt(String key, File inputFile, File outputFile) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        try (FileInputStream inputStream = new FileInputStream(inputFile);
             FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            byte[] inputBytes = new byte[64];
            int bytesRead;

            while ((bytesRead = inputStream.read(inputBytes)) != -1) {
                byte[] outputBytes = cipher.update(inputBytes, 0, bytesRead);
                if (outputBytes != null) {
                    outputStream.write(outputBytes);
                }
            }
            byte[] outputBytes = cipher.doFinal();
            if (outputBytes != null) {
                outputStream.write(outputBytes);
            }
        }
    }
}

3. 使用说明

    创建文本文件:在项目根目录下创建一个名为 example.txt 的文本文件,并添加一些内容。

    运行代码:将上述代码保存为 FileEncryptDecrypt.java,然后在命令行中编译和运行:

    bash

    javac FileEncryptDecrypt.java
    java FileEncryptDecrypt

    检查输出:运行后,你会看到两个新文件:encrypted_example.txt(加密后的文件)和 decrypted_example.txt(解密后的文件)。检查 decrypted_example.txt,确保其内容与原始文件相同。

4. 注意事项

    密钥安全:确保密钥安全,不要在代码中明文存储真实的密钥。在实际应用中,可以考虑使用环境变量或安全存储服务。
    密钥长度:AES 支持 128、192 和 256 位密钥。这里使用的是 128 位(16 字节)密钥。
    异常处理:可以根据需要添加更详细的异常处理,以便在实际应用中更好地处理错误。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3028513/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2024-08-07

  • 博文量
    589
  • 访问量
    602790