如何在java中使用AES加密.txt以外的文件?
我正在开发一个java应用程序,它允许用户加密多个文件。我使用的是128位密钥的AES。我在这项工作中有以下问题:-如何在java中使用AES加密.txt以外的文件?,java,encryption,aes,Java,Encryption,Aes,我正在开发一个java应用程序,它允许用户加密多个文件。我使用的是128位密钥的AES。我在这项工作中有以下问题:- 已实现的AES算法仅适用于.txt文件,但不适用于任何其他文件类型,如Office文档、图像等。我的问题是AES适用于所有类型的数据还是仅适用于文本文件?我搜索了很多,但找到的所有示例都使用.txt文件 目前,我将文件的内容读入一个字符串,然后对其进行加密,然后将加密的字符串写回文件。我的问题是有没有一种方法可以在不读取文件内容的情况下加密文件? 是否有一种方法可以使用AES解密
import java.io.File;
import java.io.FileInputStream;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class JavaCrypt
{
public static void main(String[] args) throws Exception {
File f=new File("D:/a.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("Original string: " +strContent.toString()+"\n");
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(strContent.toString().getBytes());
System.out.println("encrypted string: " + encrypted.toString());
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " +originalString);
}
}
如果你早一点看问题,那么你就不会有太少的时间来解决问题。第1点根本不正确。AES处理二进制数据,无论是哪种数据。如果它对您不起作用,那就是您的实现错误,您需要发布代码。很可能是编码问题,而不是与加密相关的问题。第2点为什么是字符串?只需处理二进制数据。显然,您需要读取一个文件来加密它。它还应该如何工作?魔法?@CodeInChaos第2点与第4点相关。我的意思是,第4点可以在不读取文件内容的情况下实现吗?第3点和第4点不在加密范围内。除非你想创建一个完整的虚拟文件系统。当然,在这种情况下,仍然可以一次删除整个容器。@CodeInChaos这意味着没有解决这些问题的解决方案或方法???