[英]Java CipherOutputStream not returning all bytes
I'm new to cryptography but I'm planning on using it in some later applications. 我是密码学的新手,但我打算在以后的一些应用程序中使用它。
I would like to know if there is some component I am missing in this short demo program I've made. 我想知道在我做的这个简短的演示程序中是否有一些我缺少的组件。
I know I'm making an assumption with the 300 bytes, if there is a way to get around guessing array size I would like to know, 我知道我正在做300字节的假设,如果有办法绕过猜测数组大小我想知道,
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
public class CipherStreamDemo {
private static final byte[] salt={
(byte)0xC9, (byte)0xEF, (byte)0x7D, (byte)0xFA,
(byte)0xBA, (byte)0xDD, (byte)0x24, (byte)0xA9
};
private Cipher cipher;
private final SecretKey key;
public CipherStreamDemo() throws GeneralSecurityException, IOException{
SecretKeyFactory kf=SecretKeyFactory.getInstance("DES");
KeySpec spec=new DESKeySpec(salt);
key=kf.generateSecret(spec);
cipher=Cipher.getInstance("DES");
}
public void encrypt(byte[] buf) throws IOException, GeneralSecurityException{
cipher.init(Cipher.ENCRYPT_MODE,key);
OutputStream out=new CipherOutputStream(new FileOutputStream("crypt.dat"), cipher);
out.write(buf);
out.close();
}
public byte[] decrypt() throws IOException, GeneralSecurityException{
cipher.init(Cipher.DECRYPT_MODE, key);
InputStream in=new CipherInputStream(new FileInputStream("crypt.dat"), cipher);
byte[] buf=new byte[300];
int bytes=in.read(buf);
buf=Arrays.copyOf(buf, bytes);
in.close();
return buf;
}
public static void main(String[] args) {
try{
CipherStreamDemo csd=new CipherStreamDemo();
String pass="thisisasecretpassword";
csd.encrypt(pass.getBytes());
System.out.println(new String(csd.decrypt()));
}catch(Exception e){
e.printStackTrace();
}
}
}
//Output: thisisasecretpass
You're assuming that the input is going to be exactly 300 bytes, and you're also assuming you've read it all, in a single read. 你假设输入正好是300字节,你也假设你已经读过一次,只需一次读取。 You need to keep reading until read() returns -1.
你需要继续阅读,直到read()返回-1。
I don't see any point in the object streams. 我没有在对象流中看到任何意义。 They're only adding overhead.
他们只是增加了开销。 Remove them.
删除它们。
This 这个
int bytes=in.read(buf);
is almost always wrong and should be done like 几乎总是错的,应该这样做
for(int total = bytes.length; total > 0;)
{
final int read = in.read(buf, buf.length - total, total);
if (read < 0)
{
throw new EOFException("Unexpected end of input.");
}
total -= read;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.