import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;public class Test { public static void main(String[] args) throws Exception{

KeyGenerator kg=KeyGenerator.getInstance("DESede");
kg.init(168);
Key k=kg.generateKey(); Cipher c=Cipher.getInstance("DESede");
c.init(Cipher.ENCRYPT_MODE,k);

String str="test string";
byte[] b=str.getBytes();
ByteArrayInputStream bis=new ByteArrayInputStream(b);
CipherInputStream cis=new CipherInputStream(bis,c);

System.out.println(cis.available());
}
}运行输出的结果为0。不知道问题出在什么地方,请各位指教啊!~~

解决方案 »

  1.   

    查了一下API ,里面有这么一句话:available 方法只计算已由封装的 Cipher 处理过的数据改成这样就不是0了,但为什么返回7,我就不知道了。。:import java.io.ByteArrayInputStream; 
    import java.io.IOException; 
    import java.security.InvalidKeyException; 
    import java.security.Key; 
    import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; 
    import javax.crypto.CipherInputStream; 
    import javax.crypto.KeyGenerator; 
    import javax.crypto.NoSuchPaddingException; public class test { public static void main(String[] args) throws Exception{ KeyGenerator kg=KeyGenerator.getInstance("DESede"); 
    kg.init(168); 
    Key k=kg.generateKey(); Cipher c=Cipher.getInstance("DESede"); 
    c.init(Cipher.ENCRYPT_MODE,k); String str="test string"; 
    byte[] b=str.getBytes(); 
    ByteArrayInputStream bis=new ByteArrayInputStream(b); 
    CipherInputStream cis=new CipherInputStream(bis,c); cis.read(); //加了这一行。System.out.println(cis.available()); 

      

  2.   

    明白了,谢谢楼上的!
    因为流加密了以后,内容是要改变的,所以流中的字节数量会改变。
    API上的描述:A CipherInputStream is composed of an InputStream and a Cipher so that read() methods return data that are read in from the underlying InputStream but have been additionally processed by the Cipher. 
    也就是要从基础流中读出数据,必须调用CipherInputStream中的read方法~~~~~~