如何将 C++ unsigned char* 转换为 C#?
How to convert C++ unsigned char* to C#?
我在 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);
}
当 state 和 expandedKey 是 byte[].
我在 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);
}
当 state 和 expandedKey 是 byte[].