簡體   English   中英

C#Split byte []數組

[英]C# Split byte[] array

我正在進行RSA加密,我必須將長字符串拆分為小字節[]並加密它們。 然后我組合數組並轉換為字符串並寫入安全文件。

然后加密創建字節[128]

我使用以下結合:

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;
}

當我解密時,我接受字符串,將其轉換為byte []數組,現在需要將其拆分以解碼塊然后轉換為字符串。

有任何想法嗎?

謝謝

編輯:

我認為我現在有分裂工作,但解密失敗了。 這是因為RSA密鑰等嗎? 在TimePointA它加密它,然后在TimePointB它嘗試解密它失敗。 公鑰是不同的,所以不確定是否是問題。

解密時,可以為解密緩沖區創建一個數組並重用它:

此外,通常RSA用於加密AES等對稱密鑰,對稱算法用於加密實際數據。 這是巨大的更快任何超過1個密碼塊長。 要解密數據,可以使用RSA解密對稱密鑰,然后使用該密鑰解密數據。

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
}

編輯2:如果要將數據存儲為字符串而不是原始字節,請使用Convert.ToBase64String()Convert.FromBase64String()作為最安全的轉換解決方案。

編輯3:從他的編輯:

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;
}

我會說這樣的事情會這樣做:

        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
        }

為什么需要將字符串分成可變長度的塊? 固定長度的塊,或根本沒有塊,將大大簡化這一點。

“公鑰是不同的”?

您使用私鑰進行加密,並使用與私鑰對應的公鑰進行解密。

別的什么都會給你帶來胡言亂語。

為什么不使用框架而不是自己做字節?

http://www.codinghorror.com/blog/archives/001275.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM