【发布时间】:2012-06-14 08:33:36
【问题描述】:
我正在开发一个允许用户加密多个文件的 java 应用程序。我正在使用带有 128 位密钥的 AES。我在这项工作中有以下问题:-
实现的 AES 算法仅适用于 .txt 文件,但不适用于任何其他文件类型,例如 Office 文档、图像等。我的问题是 AES 是否适用于所有类型的数据或仅文本文件?我搜索了很多,但我找到的所有示例都使用 .txt 文件。
目前我将文件的内容读入字符串,然后对其进行加密,然后将加密的字符串写回文件。我的问题是有没有办法在不读取文件内容的情况下加密文件?
有没有办法使用 AES 解密目录(文件夹)及其所有内容?“解密目录”是指无法打开它并显示一些错误消息尝试打开时。
还可以编辑、删除、移动、复制和重命名加密文件。我希望没有人可以对我的应用程序加密的文件执行这些操作。 怎么做?
以下是我正在使用的代码,但仅适用于 .txt 文件,不适用于其他文件。不知道是什么问题:
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 适用于二进制数据,无论类型如何。如果它不适合你,那是你的实现错误,你需要发布你的代码。可能这是一个编码问题,而不是加密相关问题。
-
Point 2 为什么是字符串?只需处理二进制数据。你显然需要读取一个文件来加密它。它还应该如何工作?魔法?
-
@CodeInChaos第2点和第4点有关,我的意思是不读取文件内容可以实现第4点吗?
-
第 3 点和第 4 点不在加密范围内。除非您想创建一个完整的虚拟文件系统。当然,在这种情况下,仍然可以一次删除整个容器。
-
@CodeInChaos 表示没有办法解决这些问题???
标签: java encryption aes