gpt4 book ai didi

c# - 如何将 C++ unsigned char* 转换为 C#?

转载 作者:行者123 更新时间:2023-11-30 04:53:02 24 4
gpt4 key购买 nike

我在 C++ 中为 AES 256 加密创建了一个有效的方法:

void AES_Encrypt(unsigned char* message, unsigned char* expandedKey)
{
unsigned char numOfRounds = 13;
unsigned char* state = new unsigned char[16];

AddRoundKey(state, expandedKey);
for (int i = 0; i < numOfRounds; i++)
{
//bla bla
AddRoundKey(state, expandedKey + (16 * (i + 1)));
}

// bla bla
AddRoundKey(state, expandedKey + 224);
}

void AddRoundKey(unsigned char *state, unsigned char* roundKey)
{
for (int i = 0; i < 16; i++)
state[i] = state[i] ^ roundKey[i];
}

但是当我将它翻译成 C# 时:

private void AddRoundKey(byte[] state, byte[] roundKey)
{
for (int i = 0; i < 16; i++)
state[i] = (byte)(state[i] ^ roundKey[i]);
}

我在准确翻译的函数上遇到错误:

AddRoundKey(state, expandedKey + (16 * (i + 1)));
AddRoundKey(state, expandedKey + 224);

在这种情况下,我如何正确翻译 void AddRoundKey(unsigned char *state, unsigned char* roundKey)

最佳答案

最简单的方法是传递偏移量:

void AddRoundKey(byte[] state, byte[] roundKey, int offset)
{
for (int i = 0; i < 16; i++)
state[i] = (byte)(state[i] ^ roundKey[i + offset]);
}

然后你调用它:

        AddRoundKey(state, expandedKey, (16 * (i + 1)));
...
AddRoundKey(state, expandedKey, 244);

其他

您可以使用 unsafe关键字(注意在项目设置中启用不安全)

unsafe void AddRoundKey(byte* state, byte* roundKey)
{
for (int i = 0; i < 16; i++)
state[i] = (byte)(state[i] ^ roundKey[i]);
}

然后在你调用它的时候使用 fixed:

fixed (byte* state_pointer = state, expandedKey_pointer = expandedKey)
{
AddRoundKey(state_pointer, expandedKey_pointer + 244);
}

stateexpandedKey 为 byte[] 时。

关于c# - 如何将 C++ unsigned char* 转换为 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54020396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com