使用RC4算法逐行加密后解密只有一行正确

Decryption only yields one correct line after encrypting line by line using RC4 algorithm

我必须使用 RC4 算法逐行加密文件。

加密整个文件并解密整个文件生成原始文件,这很好。

当我尝试一次读取文件一行,对其进行加密,然后将加密行写入文件时,对生成的文件进行解密只会产生一个正确的行,即原始文件的第一行。

我尝试读取文件并使用字节数组将其提供给 rc4 例程,字节数组的大小是密钥长度的倍数,但结果是一样的。这是我的尝试:

try
{
    BufferedReader br = new BufferedReader((new FileReader(fileToEncrypt)));                    
    FileOutputStream fos = new  FileOutputStream("C:\Users\nikaselo\Documents\Encryption\encrypted.csv", true);
    File file = new File("C:\Users\nikaselo\Documents\Encryption\encrypted.csv");
 // encrypt
    while ((line = br.readLine()) != null) 
    {
        byte [] encrypt = fed.RC4(line.getBytes(), pwd);

        if (encrypt != null) dos.write(encrypt);
            fos.flush();
    }

    fos.close();

// test decrypt
    FileInputStream fis = null;
    fis = new FileInputStream(file);
    byte[] input = new byte[512];
    int bytesRead;
    while ((bytesRead = fis.read(input)) != -1)
    {
        byte [] de= fed.RC4(input, pwd);
        String result = new String(de);
        System.out.println(result);
    }
}   
catch (Exception ex) 
{                                
    ex.printStackTrace();
}

这是我的 RC4 函数

public  byte []  RC4 (byte [] Str, String Pwd) throws Exception
{
    int[] Sbox = new int [256] ;
    int A, B,c,Tmp;;

    byte [] Key = {};
    byte [] ByteArray = {};

    //KEY
    if ((Pwd.length() == 0 || Str.length == 0)) 
    {
        byte [] arr = {};
        return arr;
    }
    if(Pwd.length() > 256) 
    {
        Key  = Pwd.substring(0, 256).getBytes();
    }
    else 
    {
        Key = Pwd.getBytes();
    }
    //String
    for( A = 0 ; A <= 255; A++ ) 
    {
        Sbox[A] = A;    
    }
    A = B = c= 0;
    for  (A = 0; A <= 255; A++) 
    {
        B = (B + Sbox[A] + Key[A % Pwd.length()]) % 256;    
        Tmp = Sbox[A];
        Sbox[A] = Sbox[B];
        Sbox[B] = Tmp;
    }

    A = B = c= 0;
    ByteArray = Str;
    for (A = 0; A <= Str.length -1 ; A++)
    {   
        B = (B + 1) % 256;
        c = (c + Sbox[B]) % 256;
        Tmp =  Sbox[B];
        Sbox[B] = Sbox[c];
        Sbox[c] = Tmp;
        ByteArray[A] = (byte) (ByteArray[A] ^ (Sbox[(Sbox[B] + Sbox[c]) % 256]));           
    }

    return ByteArray;
}

运行 这给了我一条清晰的线,其余的只是不可读。

您正在逐行加密,但您正试图以 512 字节块为单位进行解密。

我认为您的选择是:

  1. 以固定大小的块加密和解密
  2. 将每行填充到 512 字节(以及超过 512 字节的拆分行)
  3. 引入分隔符。这将很棘手,因为密文中可能会出现任何定界符,因此您应该对每个加密行进行 base64 编码,并用换行符将它们分开。

可能 1 是最简单的(也是真正加密中使用的那个),但如果你必须逐行执行,我会选择 3,即使这引入了一个漏洞,但它是不再被认为是安全的 RC4。