2016-04-17 15 views
2

単純に、私はCipherInputStreamを持っていて、それをバイト配列に変換したいと思います。他の投稿は役に立たなかった。これを実現するには?暗号入力ストリームをバイト配列に変換しますか?

FileInputStream fis = new FileInputStream("dataPath/data"); 
SecretKeySpec sks = new SecretKeySpec("password".getBytes(), "AES"); 
Cipher cipher = Cipher.getInstance("AES"); 
cipher.init(Cipher.DECRYPT_MODE, sks); 
CipherInputStream cis = new CipherInputStream(fis, cipher); 

cisからバイト配列を取得するにはどうすればよいですか?

答えて

3

CipherInputStreamは標準InputStreamの実装である、したがって、あなただけ例えばByteArrayOutputStreamを使用してバイト配列にそれを読むことができます:

CipherInputStream cis = ... 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
int len; 
byte[] buffer = new byte[4096]; 
while ((len = cis.read(buffer, 0, buffer.length)) != -1) { 
    baos.write(buffer, 0, len); 
} 
baos.flush(); 
byte[] cipherByteArray = baos.toByteArray(); // get the byte array 
+0

感謝を!働いた。配列に4096の代わりに256を割り当てるのは意味がありますか?私は正確なサイズを知らないけれども、それはそれほど大きくはないからです。 – solo

+0

@solo 4096はちょうどバッファサイズです。データが通常256バイトより小さいことがわかっている場合は、256を使用することもできます。 – Floern

関連する問題