Переделать unsafe код в safe - C#
Формулировка задачи:
Есть реализация криптоалгоритма Xtea с использованием unsafe кода. Как передалать его в safe?
Фрагмент, который нужно переделать.
Весь код:
Листинг программы
- fixed (byte* bufferPtr = buffer)//????????????????????
- {
- uint* words = (uint*)(bufferPtr + index);//????????????????????
Листинг программы
- public static class Xtea
- {
- public unsafe static bool Encrypt(ref byte[] buffer, ref int length, int index, uint[] key)
- {
- if (key == null)//проверяем ключ
- return false;
- int msgSize = length - index;//задаем размер с учетом индекса
- int pad = msgSize % 8;//длина блока 64 бит, должно быть 8 байт(8 байт *8 = 64 бит)
- if (pad > 0)//делаем длину меседжа 8*n
- {
- msgSize += (8 - pad);
- length = index + msgSize;
- }
- fixed (byte* bufferPtr = buffer)//????????????????????
- {
- uint* words = (uint*)(bufferPtr + index);//????????????????????
- //дальше все понятно
- for (int pos = 0; pos < msgSize / 4; pos += 2)
- {
- uint x_sum = 0, x_delta = 0x9e3779b9, x_count = 32;
- while (x_count-- > 0)
- {
- words[pos] += (words[pos + 1] << 4 ^ words[pos + 1] >> 5) + words[pos + 1] ^ x_sum
- + key[x_sum & 3];
- x_sum += x_delta;
- words[pos + 1] += (words[pos] << 4 ^ words[pos] >> 5) + words[pos] ^ x_sum
- + key[x_sum >> 11 & 3];
- }
- }
- }
- return true;
- }
- public unsafe static bool Decrypt(ref byte[] buffer, ref int length, int index, uint[] key)
- {
- if (length <= index || (length - index) % 8 > 0 || key == null)
- return false;
- fixed (byte* bufferPtr = buffer)//????????????????????
- {
- uint* words = (uint*)(bufferPtr + index);//????????????????????
- int msgSize = length - index;
- //дальше все понятно
- for (int pos = 0; pos < msgSize / 4; pos += 2)
- {
- uint x_count = 32, x_sum = 0xC6EF3720, x_delta = 0x9E3779B9;
- while (x_count-- > 0)
- {
- words[pos + 1] -= (words[pos] << 4 ^ words[pos] >> 5) + words[pos] ^ x_sum
- + key[x_sum >> 11 & 3];
- x_sum -= x_delta;
- words[pos] -= (words[pos + 1] << 4 ^ words[pos + 1] >> 5) + words[pos + 1] ^ x_sum
- + key[x_sum & 3];
- }
- }
- }
- length = (int)(BitConverter.ToUInt16(buffer, index) + 2 + index);
- return true;
- }
- }
Решение задачи: «Переделать unsafe код в safe»
textual
Листинг программы
- uint word1 = BitConverter.ToUInt32(buffer, index);
- uint word2 = BitConverter.ToUInt32(buffer, index + 4);
- uint wordn = BitConverter.ToUInt32(buffer, index + 4 * n);
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д