簡體   English   中英

如何將 C++ unsigned char* 轉換為 C#?

[英]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);
        }

stateexpandKey為 byte[] 時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM