我正在进行 RSA 加密,我必须将长字符串拆分为小字节 [] 并对其进行加密。然后我组合数组并转换为字符串并写入安全文件。
然后加密创建byte[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[] 数组,现在需要拆分它以解码 block ,然后转换为字符串。
有什么想法吗?
谢谢
编辑:
我想我现在可以拆分了,但是解密失败了。这是因为 RSA key 等吗?在 TimePointA 它对其进行加密,然后在 TimePointB 它尝试解密但失败。公钥不同,所以不确定这是否是问题所在。
最佳答案
解密时,可以为解密缓冲区创建一个数组并重复使用它:
此外,通常 RSA 用于为 AES 之类的东西加密对称 key ,而对称算法用于加密实际数据。对于超过 1 个密码 block 的任何东西,这都非常快。要解密数据,您需要使用 RSA 解密对称 key ,然后使用该 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
}
编辑 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;
}
关于C# 拆分 byte[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1163921/