2014-03-06 3 views
0

저는 암호를 처음 사용하지만 나중에 일부 응용 프로그램에서 사용할 계획입니다.Java CipherOutputStream이 모든 바이트를 반환하지 않습니다.

내가 만든 짧은 데모 프로그램에서 누락 된 구성 요소가 있는지 알고 싶습니다. 내가 알고 싶습니다 배열의 크기를 추측 주위에 얻을 수있는 방법이 있는지

나는

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 바이트로 가정을 만들고 있어요 알고 정확하게 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; 
} 
같이 수행해야합니다
관련 문제