在Node.js中加密文件可以使用crypto模块提供的功能。具体步骤如下:
const crypto = require('crypto');
const key = crypto.randomBytes(32); // 生成32字节的随机密钥
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
其中,'aes-256-gcm'表示使用AES算法,密钥长度为256位,使用GCM模式进行加密。iv是初始化向量,需要自行生成。
const fs = require('fs');
const input = fs.createReadStream('input.txt'); // 待加密的文件路径
const output = fs.createWriteStream('output.txt'); // 加密后的文件路径
input.pipe(cipher).pipe(output);
完整的代码示例:
const crypto = require('crypto');
const fs = require('fs');
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('output.txt');
input.pipe(cipher).pipe(output);
在Java中使用"AES/GCM/NoPadding"解密可以使用Java Cryptography Extension (JCE)提供的功能。具体步骤如下:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path encryptedFilePath = Paths.get("output.txt"); // 加密后的文件路径
byte[] encryptedData = Files.readAllBytes(encryptedFilePath);
byte[] keyBytes = "0123456789abcdef0123456789abcdef".getBytes(); // 密钥,需要与加密时使用的密钥一致
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(128, iv); // iv是加密时使用的初始化向量,需要与加密时一致
cipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decryptedData = cipher.doFinal(encryptedData);
Path decryptedFilePath = Paths.get("decrypted.txt"); // 解密后的文件路径
Files.write(decryptedFilePath, decryptedData);
完整的代码示例:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDecryption {
public static void main(String[] args) throws Exception {
Path encryptedFilePath = Paths.get("output.txt");
byte[] encryptedData = Files.readAllBytes(encryptedFilePath);
byte[] keyBytes = "0123456789abcdef0123456789abcdef".getBytes();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decryptedData = cipher.doFinal(encryptedData);
Path decryptedFilePath = Paths.get("decrypted.txt");
Files.write(decryptedFilePath, decryptedData);
}
}
需要注意的是,以上示例中的密钥和初始化向量(iv)都是示例值,实际使用时需要根据具体需求生成安全的随机值,并妥善保管密钥。此外,还需要根据实际情况处理异常和文件路径等细节。
领取专属 10元无门槛券
手把手带您无忧上云