在Java中,可以使用以下方法来实现文件的加密和解密:
加密文件:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
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.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,因此在实际应用中可能需要对密钥进行加密保护。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java如何实现文件加密与解密