2014-03-06 66 views
0

我是密碼學的新手,但我打算在以後的某些應用程序中使用它。Java CipherOutputStream不返回所有字節

我想知道在我製作的這個簡短演示程序中是否存在某些組件。

我知道我在做一個假設,與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 

回答

2

你假定輸入是怎麼回事精確到300字節,並且您還假設您已經閱讀了所有內容,只需一次閱讀。你需要繼續閱讀直到read()返回-1。

我在對象流中看不到任何點。他們只是增加開銷。刪除它們。

0

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; 
} 
完成