示例#1
0
        public static void WriteKeyStreamBlock(ReadOnlySpan <uint> state, ulong iv, uint numRounds, Span <byte> destination)
        {
            var destinationAsUInt = MemoryMarshal.Cast <byte, uint>(destination);
            var ivLow             = ((uint)BitwiseHelpers.ExtractLow(iv));
            var ivHigh            = ((uint)BitwiseHelpers.ExtractHigh(iv));
            var t0 = state[0];
            var t1 = state[1];
            var t2 = state[2];
            var t3 = state[3];
            var t4 = state[4];
            var t5 = state[5];
            var t6 = state[6];
            var t7 = state[7];
            var t8 = state[8];
            var t9 = state[9];
            var tA = state[10];
            var tB = state[11];
            var tC = ivLow;
            var tD = ivHigh;
            var tE = state[14];
            var tF = state[15];

            numRounds = (numRounds >> 1);

            for (var i = 0U; (i < numRounds); i++)
            {
                DoubleRound(
                    ref t0, ref t1, ref t2, ref t3,
                    ref t4, ref t5, ref t6, ref t7,
                    ref t8, ref t9, ref tA, ref tB,
                    ref tC, ref tD, ref tE, ref tF
                    );
            }

            destinationAsUInt[0]  = (t0 + state[0]);
            destinationAsUInt[1]  = (t1 + state[1]);
            destinationAsUInt[2]  = (t2 + state[2]);
            destinationAsUInt[3]  = (t3 + state[3]);
            destinationAsUInt[4]  = (t4 + state[4]);
            destinationAsUInt[5]  = (t5 + state[5]);
            destinationAsUInt[6]  = (t6 + state[6]);
            destinationAsUInt[7]  = (t7 + state[7]);
            destinationAsUInt[8]  = (t8 + state[8]);
            destinationAsUInt[9]  = (t9 + state[9]);
            destinationAsUInt[10] = (tA + state[10]);
            destinationAsUInt[11] = (tB + state[11]);
            destinationAsUInt[12] = (tC + ivLow);
            destinationAsUInt[13] = (tD + ivHigh);
            destinationAsUInt[14] = (tE + state[14]);
            destinationAsUInt[15] = (tF + state[15]);
        }
示例#2
0
        public static XChaCha20 New(ReadOnlySpan <byte> key, ReadOnlySpan <byte> nonce, ulong iv)
        {
            if (nonce.Length != 24)
            {
                throw new ArgumentOutOfRangeException(actualValue: nonce.Length, message: NONCE_LENGTH_ERROR, paramName: nameof(nonce));
            }

            var derivedKey   = ComputeHash(key, nonce.Slice(0, 16));
            var derivedNonce = (Span <byte>) stackalloc byte[12];

            BinaryPrimitives.WriteUInt32BigEndian(derivedNonce, ((uint)BitwiseHelpers.ExtractHigh(iv)));
            nonce.Slice(16, 8).CopyTo(derivedNonce.Slice(4, 8));

            return(new XChaCha20(derivedKey, derivedNonce, iv));
        }