【发布时间】:2012-11-06 09:08:30
【问题描述】:
我正在尝试编写一个简单的程序来使用 AES 算法加密和解密文件。后来的意图是在更复杂的程序中使用将简单程序拆分为加密和解密方法。 他是程序的加密部分:
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey key = kg.generateKey();
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, key);
FileInputStream fis; FileOutputStream fos; CipherOutputStream cos;
fis = new FileInputStream("FileTo.encrypt");
fos = new FileOutputStream("Encrypted.file");
//write encrypted to file
cos = new CipherOutputStream(fos, c);
byte[] b = new byte[16];
int i = fis.read(b);
while (i != -1) {
cos.write(b, 0, i);
i = fis.read(b);
}
cos.close();
//write key to file
byte[] keyEncoded = key.getEncoded();
FileOutputStream kos = new FileOutputStream("crypt.key");
kos.write(keyEncoded);
kos.close();
下面是解密部分:
//Load Key
FileInputStream fis2= new FileInputStream("a.key");
File f=new File("a.key");
long l=f.length();
byte[] b1=new byte[(int)l];
fis2.read(b1, 0, (int)l);
SecretKeySpec ks2=new SecretKeySpec(b1,"AES");
Cipher c1 = Cipher.getInstance("AES");
c1.init(Cipher.DECRYPT_MODE, ks2);
FileInputStream fis1=new FileInputStream("Encrypted.file");
CipherInputStream in= new CipherInputStream(fis1,c1);
FileOutputStream fos0 =new FileOutputStream("decrypted.file");
byte[] b3=new byte[1];
int ia=in.read(b3);
while (ia >=0)
{
c1.update(b3); //<-------remove this
fos0.write(b3, 0, ia);
ia=in.read(b3);
}
in.close();
fos0.flush();
fos0.close();
现在的问题是解密部分没有解密最后一位,有些位丢失了。在我看来,它只每 16 个字节解密一次,但是当它应该返回最后一个字节时,变量 in(cipherinputstream) 返回 -1。 我如何获得最后的位?
提前致谢
已编辑:添加注释以指出必须删除的内容。这是一些正确的代码(即,不加载整个文件在 java 中)使用 AES 加密和解密 Java 中的文件。可以添加其他参数(填充等),但这是基本代码。
【问题讨论】:
标签: java file encryption