[英]How to convert C++ unsigned char* to C#?
我有一个为 AES 256 加密创建的 C++ 方法,该方法有效:
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(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)
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和expandKey为 byte[] 时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.