2

在 C# 中,我使用 Blowfish.NET 2.1.3 的 BlowfishECB.cs 文件(可以在这里找到

在 C++ 中,它是未知的,但它是相似的。

在 C++ 中,Initialize(blowfish) 过程如下:

void cBlowFish::Initialize(BYTE key[], int keybytes)

在 C# 中,Initialize(blowfish) 过程是相同的

public void Initialize(byte[] key, int ofs, int len) 

这就是问题:

这就是在 C++ 中初始化密钥的方式

DWORD keyArray[2] = {0}; //declaration
...some code
blowfish.Initialize((LPBYTE)keyArray, 8);

如您所见,键是一个由两个 DWORD 组成的数组,总共 8 个字节。

在 C# 我这样声明它,但我得到一个错误

BlowfishECB blowfish = new BlowfishECB();
UInt32[] keyarray = new UInt32[2];
..some code
blowfish.Initialize(keyarray, 0, 8);

错误是:

参数 '1':无法从 'uint[]' 转换为 'byte[]'

我究竟做错了什么?

提前致谢!

4

3 回答 3

5

您可以使用BitConverter从 UInt32 获取字节。


为此,您需要在循环中转换每个元素。我会做类似的事情:

private byte[] ConvertFromUInt32Array(UInt32[] array)
{
    List<byte> results = new List<byte>();
    foreach(UInt32 value in array)
    {
        byte[] converted = BitConverter.GetBytes(value);
        results.AddRange(converted);
    }
    return results.ToArray();
}

回去:

private UInt32[] ConvertFromByteArray(byte[] array)
{
    List<UInt32> results = new List<UInt32>();
    for(int i=0;i<array.Length;i += 4)
    {
        byte[] temp = new byte[4];
        for (int j=0;j<4;++j)
            temp[j] = array[i+j];
        results.Add(BitConverter.ToUInt32(temp);
    }
    return results.ToArray();
}

于 2009-03-28T14:10:47.480 回答
4

如果您使用的是 VS2008 或 C# 3.5,请尝试以下 LINQ + BitConverter 解决方案

var converted = 
  keyArray
    .Select(x => BitConverter.GetBytes(x))
    .SelectMany(x => x)
    .ToArray();

打破这个

  • Select 将每个 UInt32 转换为 byte[]。结果是一个 IEnumerable<byte[]>
  • SelectMany 调用将 IEnumerable<byte[]> 扁平化为 IEnumerable<byte>
  • ToArray() 只是将可枚举转换为数组

编辑同样有效的非 LINQ 解决方案

List<byte> list = new List<byte>();
foreach ( UInt32 k in keyArray) {
  list.AddRange(BitConverter.GetBytes(k));
}
return list.ToArray();
于 2009-03-28T14:22:53.597 回答
0

如果您需要一种更快的方法来转换值类型,可以使用我在以下答案中描述的技巧:将 float[] 转换为 byte[] 的最快方法是什么?

这种 hack 避免了内存分配和迭代。它为您提供了 O(1) 中数组的不同视图。

当然,只有在性能有问题时才应该使用它(避免过早优化)。

于 2012-03-12T11:43:00.693 回答