summary refs log tree commit diff
path: root/crypto/src/crypto/engines/HC256Engine.cs
blob: 1ace7bbc0676e6e5611a2b1e1ae095a703d00272 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using System;

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Crypto.Engines
{
    /**
	* HC-256 is a software-efficient stream cipher created by Hongjun Wu. It 
	* generates keystream from a 256-bit secret key and a 256-bit initialization 
	* vector.
	* <p>
	* http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc256_p3.pdf
	* </p><p>
	* Its brother, HC-128, is a third phase candidate in the eStream contest.
	* The algorithm is patent-free. No attacks are known as of today (April 2007). 
	* See
	* 
	* http://www.ecrypt.eu.org/stream/hcp3.html
	* </p>
	*/
    public class HC256Engine
		: IStreamCipher
	{
		private readonly uint[] p = new uint[1024];
		private readonly uint[] q = new uint[1024];
		private uint cnt = 0;

		private uint Step()
		{
			uint j = cnt & 0x3FF;
			uint ret;
			if (cnt < 1024)
			{
				uint x = p[(j - 3) & 0x3FF];
				uint y = p[(j - 1023) & 0x3FF];
				p[j] += p[(j - 10) & 0x3FF]
					+ (Integers.RotateRight(x, 10) ^ Integers.RotateRight(y, 23))
					+ q[(x ^ y) & 0x3FF];

				x = p[(j - 12) & 0x3FF];
				ret = (q[x & 0xFF] + q[((x >> 8) & 0xFF) + 256]
					+ q[((x >> 16) & 0xFF) + 512] + q[((x >> 24) & 0xFF) + 768])
					^ p[j];
			}
			else
			{
				uint x = q[(j - 3) & 0x3FF];
				uint y = q[(j - 1023) & 0x3FF];
				q[j] += q[(j - 10) & 0x3FF]
					+ (Integers.RotateRight(x, 10) ^ Integers.RotateRight(y, 23))
					+ p[(x ^ y) & 0x3FF];

				x = q[(j - 12) & 0x3FF];
				ret = (p[x & 0xFF] + p[((x >> 8) & 0xFF) + 256]
					+ p[((x >> 16) & 0xFF) + 512] + p[((x >> 24) & 0xFF) + 768])
					^ q[j];
			}
			cnt = (cnt + 1) & 0x7FF;
			return ret;
		}

		private byte[] key, iv;
		private bool initialised;

		private void Init()
		{
			if (key.Length != 32 && key.Length != 16)
				throw new ArgumentException("The key must be 128/256 bits long");
			if (iv.Length < 16)
				throw new ArgumentException("The IV must be at least 128 bits long");

			if (key.Length != 32)
	        {
				byte[] k = new byte[32];

				Array.Copy(key, 0, k, 0, key.Length);
				Array.Copy(key, 0, k, 16, key.Length);

				key = k;
			}

			if (iv.Length < 32)
			{
				byte[] newIV = new byte[32];

				Array.Copy(iv, 0, newIV, 0, iv.Length);
				Array.Copy(iv, 0, newIV, iv.Length, newIV.Length - iv.Length);

				iv = newIV;
			}

            idx = 0;
			cnt = 0;

			uint[] w = new uint[2560];

			Pack.LE_To_UInt32(key, 0, w, 0, 8);
            Pack.LE_To_UInt32(iv, 0, w, 8, 8);

			for (uint i = 16; i < 2560; i++)
			{
				uint x = w[i - 2];
				uint y = w[i - 15];
				w[i] = (Integers.RotateRight(x, 17) ^ Integers.RotateRight(x, 19) ^ (x >> 10))
					+ w[i - 7]
					+ (Integers.RotateRight(y, 7) ^ Integers.RotateRight(y, 18) ^ (y >> 3))
					+ w[i - 16] + i;
			}

			Array.Copy(w, 512, p, 0, 1024);
			Array.Copy(w, 1536, q, 0, 1024);

			for (int i = 0; i < 4096; i++)
			{
				Step();
			}

			cnt = 0;
		}

        public virtual string AlgorithmName => "HC-256";

		/**
		* Initialise a HC-256 cipher.
		*
		* @param forEncryption whether or not we are for encryption. Irrelevant, as
		*                      encryption and decryption are the same.
		* @param params        the parameters required to set up the cipher.
		* @throws ArgumentException if the params argument is
		*                                  inappropriate (ie. the key is not 256 bit long).
		*/
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
		{
            if (!(parameters is ParametersWithIV ivParams))
                throw new ArgumentException("HC-256 Init parameters must include an IV");

            if (!(ivParams.Parameters is KeyParameter keyParams))
            {
                throw new ArgumentException(
                    "Invalid parameter passed to HC256 init - " + Platform.GetTypeName(parameters),
                    "parameters");
            }

            key = keyParams.GetKey();
            iv = ivParams.GetIV();

            Init();

            initialised = true;
        }

        private readonly byte[] buf = new byte[4];
		private int idx = 0;

		private byte GetByte()
		{
			if (idx == 0)
			{
				Pack.UInt32_To_LE(Step(), buf);
			}
			byte ret = buf[idx];
			idx = (idx + 1) & 0x3;
			return ret;
		}

        public virtual void ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
		{
			if (!initialised)
				throw new InvalidOperationException(AlgorithmName + " not initialised");

            Check.DataLength(input, inOff, len, "input buffer too short");
            Check.OutputLength(output, outOff, len, "output buffer too short");

            for (int i = 0; i < len; i++)
			{
				output[outOff + i] = (byte)(input[inOff + i] ^ GetByte());
			}
		}

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public virtual void ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
        {
            if (!initialised)
                throw new InvalidOperationException(AlgorithmName + " not initialised");

            Check.OutputLength(output, input.Length, "output buffer too short");

            for (int i = 0; i < input.Length; i++)
            {
                output[i] = (byte)(input[i] ^ GetByte());
            }
        }
#endif

        public virtual void Reset()
		{
			Init();
		}

        public virtual byte ReturnByte(byte input)
		{
			return (byte)(input ^ GetByte());
		}
	}
}