繁体   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