Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Split byte[] array

I am doing RSA encryption and I have to split my long string into small byte[] and encrypt them. I then combine the arrays and convert to string and write to a secure file.

Then encryption creates byte[128]

I use this the following to combine:

public static byte[] Combine(params byte[][] arrays)
{
    byte[] ret = new byte[arrays.Sum(x => x.Length)];
    int offset = 0;
    foreach (byte[] data in arrays)
    {
        Buffer.BlockCopy(data, 0, ret, offset, data.Length);
        offset += data.Length;
    }
    return ret;
}

When I decrypt I take the string, convert it to a byte[] array and now need to split it to decode the chunks and then convert to string.

Any ideas?

Thanks

EDIT:

I think I have the split working now however the decryption fails. Is this because of RSA keys etc? At TimePointA it encrypts it, then at TimePointB it tries to decrypt and it fails. The public keys are different so not sure if that is the issue.

like image 349
Jon Avatar asked Jul 22 '09 08:07

Jon


2 Answers

When you decrypt, you can create one array for your decrypt buffer and reuse it:

Also, normally RSA gets used to encrypt a symmetric key for something like AES, and the symmetric algorithm is used to encrypt the actual data. This is enormously faster for anything longer than 1 cipher block. To decrypt the data, you decrypt the symmetric key with RSA, followed by decrypting the data with that key.

byte[] buffer = new byte[BlockLength];
// ASSUMES SOURCE IS padded to BlockLength
for (int i = 0; i < source.Length; i += BlockLength)
{
    Buffer.BlockCopy(source, i, buffer, 0, BlockLength);
    // ... decode buffer and copy the result somewhere else
}

Edit 2: If you are storing the data as strings and not as raw bytes, use Convert.ToBase64String() and Convert.FromBase64String() as the safest conversion solution.

Edit 3: From his edit:

private static List<byte[]> splitByteArray(string longString)
{
    byte[] source = Convert.FromBase64String(longString);
    List<byte[]> result = new List<byte[]>();

    for (int i = 0; i < source.Length; i += 128)
    {
        byte[] buffer = new byte[128];
        Buffer.BlockCopy(source, i, buffer, 0, 128);
        result.Add(buffer);
    }
    return result;
}
like image 96
Sam Harwell Avatar answered Sep 19 '22 09:09

Sam Harwell


I'd say something like this would do it:

        byte[] text = Encoding.UTF8.GetBytes(longString);
        int len = 128;

        for (int i = 0; i < text.Length; )
        {
            int j = 0;
            byte[] chunk = new byte[len];
            while (++j < chunk.Length && i < text.Length)
            {
                chunk[j] = text[i++];
            }
            Convert(chunk); //do something with the chunk
        }
like image 29
Matt Jacobsen Avatar answered Sep 20 '22 09:09

Matt Jacobsen