コード例 #1
0
        private void XteaEncrypt(OutputMessage message)
        {
            AddMessageLength(message);

            int encryptedSize = message.GetBufferLength();

            if ((encryptedSize % 8) != 0)
            {
                int n = 8 - (encryptedSize % 8);
                message.AddPaddingBytes(n);
                encryptedSize += n;
            }

            int indexedSize = message.GetBufferLength();

            byte[] buffer = message.GetIndexedBuffer(indexedSize);

            int readPos = 0;

            while (readPos < encryptedSize / 4)
            {
                uint v0    = BitConverter.ToUInt32(buffer, readPos * 4);
                uint v1    = BitConverter.ToUInt32(buffer, (readPos + 1) * 4);
                uint delta = 0x61C88647;
                uint sum   = 0;

                for (int i = 0; i < 32; i++)
                {
                    v0  += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + m_XteaKey[sum & 3]);
                    sum -= delta;
                    v1  += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + m_XteaKey[sum >> 11 & 3]);
                }

                int tmpReadPos = 0;

                byte[] v0Array = BitConverter.GetBytes(v0);
                byte[] v1Array = BitConverter.GetBytes(v1);
                foreach (byte v in v0Array)
                {
                    buffer[readPos * 4 + tmpReadPos++] = v;
                }
                foreach (byte v in v1Array)
                {
                    buffer[readPos * 4 + tmpReadPos++] = v;
                }

                readPos += 2;
            }

            message.ReplaceIndexedBuffer(buffer);
        }