您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,可以使用多种算法实现文件的加密和解密。这里,我将向您展示如何使用Java内置的Cipher
类来实现AES加密和解密。首先,确保已经将Java加密扩展(Java Cryptography Extension, JCE)添加到项目中。
以下是一个简单的示例,展示了如何使用AES算法对文件进行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
public class FileEncryptionDecryption {
private static final String AES = "AES";
private static final String CHARSET_NAME = "UTF-8";
public static void main(String[] args) throws Exception {
String inputFile = "input.txt";
String encryptedFile = "encrypted.txt";
String decryptedFile = "decrypted.txt";
// 生成密钥
SecretKey secretKey = generateSecretKey();
// 加密文件
encryptFile(inputFile, encryptedFile, secretKey);
// 解密文件
decryptFile(encryptedFile, decryptedFile, secretKey);
}
private static SecretKey generateSecretKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(128);
return keyGenerator.generateKey();
}
private static void encryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception {
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
Cipher cipher = Cipher.getInstance(AES)) {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] encryptedBytes = cipher.update(buffer, 0, bytesRead);
if (encryptedBytes != null) {
outputStream.write(encryptedBytes);
}
}
byte[] finalBytes = cipher.doFinal();
if (finalBytes != null) {
outputStream.write(finalBytes);
}
}
}
private static void decryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception {
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
Cipher cipher = Cipher.getInstance(AES)) {
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] decryptedBytes = cipher.update(buffer, 0, bytesRead);
if (decryptedBytes != null) {
outputStream.write(decryptedBytes);
}
}
byte[] finalBytes = cipher.doFinal();
if (finalBytes != null) {
outputStream.write(finalBytes);
}
}
}
}
这个示例中,我们首先生成一个AES密钥,然后使用该密钥对文件进行加密和解密。请注意,这个示例仅用于演示目的,实际应用中可能需要更多的错误处理和功能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。