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

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

加密文件:

创建一个密钥

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();

创建一个Cipher对象并设置加密模式

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

读取文件内容并进行加密

byte[] fileBytes = Files.readAllBytes(Paths.get("input.txt"));
byte[] encryptedBytes = cipher.doFinal(fileBytes);

将加密后的内容写入文件

Files.write(Paths.get("encrypted.txt"), encryptedBytes);

解密文件:

创建一个Cipher对象并设置解密模式

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);

读取加密文件内容并进行解密

byte[] encryptedBytes = Files.readAllBytes(Paths.get("encrypted.txt"));
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

将解密后的内容写入文件

Files.write(Paths.get("decrypted.txt"), decryptedBytes);

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

阅读剩余
THE END