为什么RC4无法处理大量加密数据?

时间:2011-06-17 13:41:51

标签: java security encryption bouncycastle jce

我有以下解密文件的代码。

package encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Decrypter {

    private static final String PASSWORD = "t_9Y#i@eT[h3}-7!";
    private static final String KEY_ALGORITHM = "PBEWithMD5AndDES";
    private static final String CIPHER_ALGORITHM = "RC4"; //Using Salsa20 or HC256 solves the problem
    private static final String PROVIDER = "BC";

    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        File inputFile = new File(args[0]);
        File outputFile = new File(args[1]);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD.toCharArray()));

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);

        InputStream inputStream = new FileInputStream(inputFile);
        OutputStream outputStream = new FileOutputStream(outputFile);

        CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);

        byte []byteBuffer = new byte[(int)inputFile.length()]; 
        cipherInputStream.read(byteBuffer);
        outputStream.write(byteBuffer); //Only 512bytes of decrypted data is written to file, the rest becomes null
        outputStream.close();
    }

}

我的问题是我做错了什么?为什么RC4不解密大小超过512字节的块。

3 个答案:

答案 0 :(得分:7)

RC4是一个流密码,因此它可以解码任何数量的数据。您的问题是没有大量的块读取InputStreams。通常,您会循环读取调用,直到没有剩余数据要读取并使用小缓冲区。请参阅documentation of read()

这可以实现为

while(true) {
    int numRead = cipherInputStream.read(byteBuffer);
    if(numRead == -1)
        break;
    outputStream.write(byteBuffer, 0, numRead);
}

答案 1 :(得分:2)

@Michael Lowman有正确的答案,但我想我会用另一种方式来宣传DataInputStream类的一个功能。

通过使用DataInputStream.readFully()方法,您可以像perl slurp一样阅读一体化行为。在您的示例中,您可以使用此方法读取字节,然后使用CipherOutputStream而不是CipherInputStream将其写出并解密。

以下面的片段为例:

    byte[] byteBuffer = new byte[(int) inputFile.length()];
    DataInputStream dis = new DataInputStream(inputStream);
    dis.readFully(byteBuffer);
    dis.close();
    CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);
    cos.write(byteBuffer);
    cos.close();

答案 2 :(得分:0)

InputStream.read只返回一定数量的数据,你应该循环直到流为空。但是我建议你使用commons-io的org.apache.commons.io.FileUtils.copyInputStreamToFile(InputStream, File)来复制流而不是自己滚动......