Java

java怎么实现文件加密与解密

小亿
143
2024-06-07 09:59:23
栏目: 编程语言

在Java中,可以使用以下方法来实现文件的加密和解密:

加密文件:

  1. 创建一个密钥
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
  1. 创建一个Cipher对象并设置加密模式
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  1. 读取文件内容并进行加密
byte[] fileBytes = Files.readAllBytes(Paths.get("input.txt"));
byte[] encryptedBytes = cipher.doFinal(fileBytes);
  1. 将加密后的内容写入文件
Files.write(Paths.get("encrypted.txt"), encryptedBytes);

解密文件:

  1. 创建一个Cipher对象并设置解密模式
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
  1. 读取加密文件内容并进行解密
byte[] encryptedBytes = Files.readAllBytes(Paths.get("encrypted.txt"));
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
  1. 将解密后的内容写入文件
Files.write(Paths.get("decrypted.txt"), decryptedBytes);

需要注意的是,加密和解密文件时需要使用相同的密钥。另外,由于使用了对称加密算法AES,因此在实际应用中可能需要对密钥进行加密保护。

0
看了该问题的人还看了