繁体   English   中英

Java CipherOutputStream不返回所有字节

[英]Java CipherOutputStream not returning all bytes

我是密码学的新手,但我打算在以后的一些应用程序中使用它。

我想知道在我做的这个简短的演示程序中是否有一些我缺少的组件。

我知道我正在做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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM