Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GF2mMatrix.java « linearalgebra « math « pqc « spongycastle « org « java « main « src « core - gitlab.com/quite/humla-spongycastle.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d2989bcfd202b6cf51d3736af6eb79c9c9bd2f80 (plain)
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package org.spongycastle.pqc.math.linearalgebra;

/**
 * This class describes some operations with matrices over finite field <i>GF(2<sup>m</sup>)</i>
 * with small <i>m</i> (1&lt; m &lt;32).
 *
 * @see Matrix
 */
public class GF2mMatrix
    extends Matrix
{

    /**
     * finite field GF(2^m)
     */
    protected GF2mField field;

    /**
     * For the matrix representation the array of type int[][] is used, thus
     * every element of the array keeps one element of the matrix (element from
     * finite field GF(2^m))
     */
    protected int[][] matrix;

    /**
     * Constructor.
     *
     * @param field a finite field GF(2^m)
     * @param enc   byte[] matrix in byte array form
     */
    public GF2mMatrix(GF2mField field, byte[] enc)
    {

        this.field = field;

        // decode matrix
        int d = 8;
        int count = 1;
        while (field.getDegree() > d)
        {
            count++;
            d += 8;
        }

        if (enc.length < 5)
        {
            throw new IllegalArgumentException(
                " Error: given array is not encoded matrix over GF(2^m)");
        }

        this.numRows = ((enc[3] & 0xff) << 24) ^ ((enc[2] & 0xff) << 16)
            ^ ((enc[1] & 0xff) << 8) ^ (enc[0] & 0xff);

        int n = count * this.numRows;

        if ((this.numRows <= 0) || (((enc.length - 4) % n) != 0))
        {
            throw new IllegalArgumentException(
                " Error: given array is not encoded matrix over GF(2^m)");
        }

        this.numColumns = (enc.length - 4) / n;

        matrix = new int[this.numRows][this.numColumns];
        count = 4;
        for (int i = 0; i < this.numRows; i++)
        {
            for (int j = 0; j < this.numColumns; j++)
            {
                for (int jj = 0; jj < d; jj += 8)
                {
                    matrix[i][j] ^= (enc[count++] & 0x000000ff) << jj;
                }
                if (!this.field.isElementOfThisField(matrix[i][j]))
                {
                    throw new IllegalArgumentException(
                        " Error: given array is not encoded matrix over GF(2^m)");
                }
            }
        }
    }

    /**
     * Copy constructor.
     *
     * @param other another {@link GF2mMatrix}
     */
    public GF2mMatrix(GF2mMatrix other)
    {
        numRows = other.numRows;
        numColumns = other.numColumns;
        field = other.field;
        matrix = new int[numRows][];
        for (int i = 0; i < numRows; i++)
        {
            matrix[i] = IntUtils.clone(other.matrix[i]);
        }
    }

    /**
     * Constructor.
     *
     * @param field  a finite field GF(2^m)
     * @param matrix the matrix as int array. Only the reference is copied.
     */
    protected GF2mMatrix(GF2mField field, int[][] matrix)
    {
        this.field = field;
        this.matrix = matrix;
        numRows = matrix.length;
        numColumns = matrix[0].length;
    }

    /**
     * @return a byte array encoding of this matrix
     */
    public byte[] getEncoded()
    {
        int d = 8;
        int count = 1;
        while (field.getDegree() > d)
        {
            count++;
            d += 8;
        }

        byte[] bf = new byte[this.numRows * this.numColumns * count + 4];
        bf[0] = (byte)(this.numRows & 0xff);
        bf[1] = (byte)((this.numRows >>> 8) & 0xff);
        bf[2] = (byte)((this.numRows >>> 16) & 0xff);
        bf[3] = (byte)((this.numRows >>> 24) & 0xff);

        count = 4;
        for (int i = 0; i < this.numRows; i++)
        {
            for (int j = 0; j < this.numColumns; j++)
            {
                for (int jj = 0; jj < d; jj += 8)
                {
                    bf[count++] = (byte)(matrix[i][j] >>> jj);
                }
            }
        }

        return bf;
    }

    /**
     * Check if this is the zero matrix (i.e., all entries are zero).
     *
     * @return <tt>true</tt> if this is the zero matrix
     */
    public boolean isZero()
    {
        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numColumns; j++)
            {
                if (matrix[i][j] != 0)
                {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Compute the inverse of this matrix.
     *
     * @return the inverse of this matrix (newly created).
     */
    public Matrix computeInverse()
    {
        if (numRows != numColumns)
        {
            throw new ArithmeticException("Matrix is not invertible.");
        }

        // clone this matrix
        int[][] tmpMatrix = new int[numRows][numRows];
        for (int i = numRows - 1; i >= 0; i--)
        {
            tmpMatrix[i] = IntUtils.clone(matrix[i]);
        }

        // initialize inverse matrix as unit matrix
        int[][] invMatrix = new int[numRows][numRows];
        for (int i = numRows - 1; i >= 0; i--)
        {
            invMatrix[i][i] = 1;
        }

        // simultaneously compute Gaussian reduction of tmpMatrix and unit
        // matrix
        for (int i = 0; i < numRows; i++)
        {
            // if diagonal element is zero
            if (tmpMatrix[i][i] == 0)
            {
                boolean foundNonZero = false;
                // find a non-zero element in the same column
                for (int j = i + 1; j < numRows; j++)
                {
                    if (tmpMatrix[j][i] != 0)
                    {
                        // found it, swap rows ...
                        foundNonZero = true;
                        swapColumns(tmpMatrix, i, j);
                        swapColumns(invMatrix, i, j);
                        // ... and quit searching
                        j = numRows;
                        continue;
                    }
                }
                // if no non-zero element was found
                if (!foundNonZero)
                {
                    // the matrix is not invertible
                    throw new ArithmeticException("Matrix is not invertible.");
                }
            }

            // normalize i-th row
            int coef = tmpMatrix[i][i];
            int invCoef = field.inverse(coef);
            multRowWithElementThis(tmpMatrix[i], invCoef);
            multRowWithElementThis(invMatrix[i], invCoef);

            // normalize all other rows
            for (int j = 0; j < numRows; j++)
            {
                if (j != i)
                {
                    coef = tmpMatrix[j][i];
                    if (coef != 0)
                    {
                        int[] tmpRow = multRowWithElement(tmpMatrix[i], coef);
                        int[] tmpInvRow = multRowWithElement(invMatrix[i], coef);
                        addToRow(tmpRow, tmpMatrix[j]);
                        addToRow(tmpInvRow, invMatrix[j]);
                    }
                }
            }
        }

        return new GF2mMatrix(field, invMatrix);
    }

    private static void swapColumns(int[][] matrix, int first, int second)
    {
        int[] tmp = matrix[first];
        matrix[first] = matrix[second];
        matrix[second] = tmp;
    }

    private void multRowWithElementThis(int[] row, int element)
    {
        for (int i = row.length - 1; i >= 0; i--)
        {
            row[i] = field.mult(row[i], element);
        }
    }

    private int[] multRowWithElement(int[] row, int element)
    {
        int[] result = new int[row.length];
        for (int i = row.length - 1; i >= 0; i--)
        {
            result[i] = field.mult(row[i], element);
        }
        return result;
    }

    /**
     * Add one row to another.
     *
     * @param fromRow the addend
     * @param toRow   the row to add to
     */
    private void addToRow(int[] fromRow, int[] toRow)
    {
        for (int i = toRow.length - 1; i >= 0; i--)
        {
            toRow[i] = field.add(fromRow[i], toRow[i]);
        }
    }

    public Matrix rightMultiply(Matrix a)
    {
        throw new RuntimeException("Not implemented.");
    }

    public Matrix rightMultiply(Permutation perm)
    {
        throw new RuntimeException("Not implemented.");
    }

    public Vector leftMultiply(Vector vector)
    {
        throw new RuntimeException("Not implemented.");
    }

    public Vector rightMultiply(Vector vector)
    {
        throw new RuntimeException("Not implemented.");
    }

    /**
     * Checks if given object is equal to this matrix. The method returns false
     * whenever the given object is not a matrix over GF(2^m).
     *
     * @param other object
     * @return true or false
     */
    public boolean equals(Object other)
    {

        if (other == null || !(other instanceof GF2mMatrix))
        {
            return false;
        }

        GF2mMatrix otherMatrix = (GF2mMatrix)other;

        if ((!this.field.equals(otherMatrix.field))
            || (otherMatrix.numRows != this.numColumns)
            || (otherMatrix.numColumns != this.numColumns))
        {
            return false;
        }

        for (int i = 0; i < this.numRows; i++)
        {
            for (int j = 0; j < this.numColumns; j++)
            {
                if (this.matrix[i][j] != otherMatrix.matrix[i][j])
                {
                    return false;
                }
            }
        }

        return true;
    }

    public int hashCode()
    {
        int hash = (this.field.hashCode() * 31 + numRows) * 31 + numColumns;
        for (int i = 0; i < this.numRows; i++)
        {
            for (int j = 0; j < this.numColumns; j++)
            {
                hash = hash * 31 + matrix[i][j];
            }
        }
        return hash;
    }

    public String toString()
    {
        String str = this.numRows + " x " + this.numColumns + " Matrix over "
            + this.field.toString() + ": \n";

        for (int i = 0; i < this.numRows; i++)
        {
            for (int j = 0; j < this.numColumns; j++)
            {
                str = str + this.field.elementToStr(matrix[i][j]) + " : ";
            }
            str = str + "\n";
        }

        return str;
    }

}