Java CipherOutputStream未返回所有字节

Java CipherOutputStream未返回所有字节,java,encryption,des,Java,Encryption,Des,我对密码学还不熟悉,但我计划在以后的一些应用程序中使用它 我想知道,在我制作的这个简短的演示程序中,是否缺少一些组件 我知道我在用300字节做一个假设,若有办法绕过我想知道的数组大小的猜测 import java.io.*; import java.security.GeneralSecurityException; import java.security.spec.KeySpec; import java.util.Arrays; import javax.crypto.*; impor

我对密码学还不熟悉,但我计划在以后的一些应用程序中使用它

我想知道,在我制作的这个简短的演示程序中,是否缺少一些组件

我知道我在用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

您假设输入正好是300字节,并且您还假设您已经在一次读取中读取了所有内容。您需要一直读取,直到read()返回-1

我在对象流中看不到任何点。他们只会增加开销。移除它们。

int bytes=in.read(buf);
几乎总是错误的,应该这样做

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;
}
for(int-total=bytes.length;total>0;)
{
最终整数读取=英寸读取(基本单位,基本单位长度-总计,总计);
如果(读取<0)
{
抛出新的EOFEException(“输入意外结束”);
}
总计-=读取;
}