在Java中,NIO(New I/O)库提供了非阻塞I/O操作,但它本身并不直接提供数据加密和解密功能。要实现数据的加密和解密,你需要使用Java的加密框架,如Java Cryptography Extension (JCE)。
以下是一个使用Java NIO和JCE实现数据加密和解密的示例:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class CryptoUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static SecretKey generateKey(int n) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(n);
return keyGenerator.generateKey();
}
public static void encryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception {
doCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile, secretKey);
}
public static void decryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception {
doCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile, secretKey);
}
private static void doCrypto(int cipherMode, String inputFile, String outputFile, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
FileChannel inputChannel = inputStream.getChannel();
FileChannel outputChannel = outputStream.getChannel()) {
ByteBuffer inputBuffer = ByteBuffer.allocateDirect(1024);
ByteBuffer outputBuffer = ByteBuffer.allocateDirect(1024);
while (inputChannel.read(inputBuffer) != -1) {
inputBuffer.flip();
outputBuffer.clear();
cipher.update(inputBuffer, outputBuffer);
outputChannel.write(outputBuffer);
inputBuffer.compact();
}
outputBuffer.put(cipher.doFinal());
outputChannel.write(outputBuffer);
}
}
}
CryptoUtil类加密和解密文件:public class Main {
public static void main(String[] args) {
try {
SecretKey secretKey = CryptoUtil.generateKey(128);
String inputFile = "input.txt";
String encryptedFile = "encrypted.txt";
String decryptedFile = "decrypted.txt";
// 加密文件
CryptoUtil.encryptFile(inputFile, encryptedFile, secretKey);
System.out.println("文件加密完成");
// 解密文件
CryptoUtil.decryptFile(encryptedFile, decryptedFile, secretKey);
System.out.println("文件解密完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个示例中,我们使用了AES算法进行加密和解密。你可以根据需要更改算法和参数。注意,这个示例使用了ECB模式,但ECB模式不推荐用于实际应用,因为它不提供足够的安全性。在实际应用中,建议使用更安全的模式,如CBC或GCM。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。