2012-04-19 5 views
1

私たちは、ストリームにデータを暗号化するためにはBouncyCastle(Android用実際SpongyCastle)フグをラップするクラスを持っている:私たちの元のコードはに書き込む前に、全体のバイト配列を暗号化 ふぐのコードは同等であるが、ではないはずです

public class BlowfishOutputStream extends OutputStream 
{ 
    private final OutputStream os; 
    private final PaddedBufferedBlockCipher bufferedCipher; 

単一操作

public void write(byte[] raw, int offset, int length) throws IOException 
{ 
    byte[] out = new byte[bufferedCipher.getOutputSize(length)]; 
    int result = this.bufferedCipher.processBytes(raw, 0, length, out, 0); 
    if (result > 0) 
    { 
     this.os.write(out, 0, result); 
    } 
} 

で出力ストリーム(一度のデータ、すなわち大量の)画像を送信することは一度にメモリ内に保持されている2枚のコピーになります。

次のコードは同等であることを意図していますが、そうではありません。理由はわかりません。私はデータが送信されていることを確認することができます(c2の合計はlengthと同等です)が、私たちのサーバーで受信された中間プロセスは、到着したものを見る前にイメージを破棄します。この段階で私が知っているのは、初期コードを使用すると応答が受信され、インクルードされた画像が抽出され、置換コードが使用されたときに応答が受信され(受け入れられる)画像は抽出されないように見えるということです。ストリームが閉じられたときに呼び出されるような問題は、ないによるdoFinalに欠けているの呼び出しであることが

public void write(byte[] raw, int offset, int length) throws IOException 
{ 
    // write to the output stream as we encrypt, not all at once. 
    final byte[] inBuffer = new byte[Constants.ByteBufferSize]; 
    final byte[] outBuffer = new byte[Constants.ByteBufferSize]; 
    ByteArrayInputStream bis = new ByteArrayInputStream(raw); 
    // read into inBuffer, encrypt into outBuffer and write to output stream 
    for (int len; (len = bis.read(inBuffer)) != -1;) 
    { 
     int c2 = this.bufferedCipher.processBytes(inBuffer, 0, len, outBuffer, 0); 
     this.os.write(outBuffer, 0, c2); 
    } 
} 

注意。確認

public void close() throws IOException 
{ 
    byte[] out = new byte[bufferedCipher.getOutputSize(0)]; 
    int result = this.bufferedCipher.doFinal(out, 0); 
    if (result > 0) 
    { 
     this.os.write(out, 0, result); 
    } 
    *nb try/catch omitted* 
} 
+0

私は第2のアルゴリズムは、渡された 'length'を尊重し、代わりにraw''の全体を想定していない溶液を、持っていると思いますメッセージです。今すぐテスト。 –

答えて

2

、皮肉にも問題はイメージではなく、以前のデータではありませんでしたが、そのデータは完全rawバイト配列ではなく指定されただけで範囲を書いたが。その場でバイト配列を暗号化するための同等のコードは次のとおりです。

@Override 
public void write(byte[] raw, int offset, int length) throws IOException 
{ 
    // write to the stream as we encrypt, not all at once. 
    final byte[] inBuffer = new byte[Constants.ByteBufferSize]; 
    final byte[] outBuffer = new byte[Constants.ByteBufferSize]; 
    int readStart = offset; 
    // read into inBuffer, encrypt into outBuffer and write to output stream 
    while(readStart<length) 
    { 
     int readAmount = Math.min(length-readStart, inBuffer.length); 
     System.arraycopy(raw, readStart, inBuffer, 0, readAmount); 
     readStart+=readAmount; 
     int c2 = this.bufferedCipher.processBytes(inBuffer, 0, readAmount, outBuffer, 0); 
     this.os.write(outBuffer, 0, c2); 
    } 
} 
+0

であり、inBufferを省略し、 'readStart'から' raw'を読み込み、 'inBuffer.length'ではなくByteBufferSizeを使う方が少し良いです。 Androidはバイト[8x1024](8k)のバッファ –

関連する問題