summaryrefslogtreecommitdiffstats
path: root/bcprov/src/main/java/org/bouncycastle/pqc/math/linearalgebra/ByteUtils.java
blob: 5ad91f4118236b9a5c1dc54c619805308d873b61 (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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package org.bouncycastle.pqc.math.linearalgebra;

/**
 * This class is a utility class for manipulating byte arrays.
 */
public final class ByteUtils
{

    private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * Default constructor (private)
     */
    private ByteUtils()
    {
        // empty
    }

    /**
     * Compare two byte arrays (perform null checks beforehand).
     *
     * @param left  the first byte array
     * @param right the second byte array
     * @return the result of the comparison
     */
    public static boolean equals(byte[] left, byte[] right)
    {
        if (left == null)
        {
            return right == null;
        }
        if (right == null)
        {
            return false;
        }

        if (left.length != right.length)
        {
            return false;
        }
        boolean result = true;
        for (int i = left.length - 1; i >= 0; i--)
        {
            result &= left[i] == right[i];
        }
        return result;
    }

    /**
     * Compare two two-dimensional byte arrays. No null checks are performed.
     *
     * @param left  the first byte array
     * @param right the second byte array
     * @return the result of the comparison
     */
    public static boolean equals(byte[][] left, byte[][] right)
    {
        if (left.length != right.length)
        {
            return false;
        }

        boolean result = true;
        for (int i = left.length - 1; i >= 0; i--)
        {
            result &= ByteUtils.equals(left[i], right[i]);
        }

        return result;
    }

    /**
     * Compare two three-dimensional byte arrays. No null checks are performed.
     *
     * @param left  the first byte array
     * @param right the second byte array
     * @return the result of the comparison
     */
    public static boolean equals(byte[][][] left, byte[][][] right)
    {
        if (left.length != right.length)
        {
            return false;
        }

        boolean result = true;
        for (int i = left.length - 1; i >= 0; i--)
        {
            if (left[i].length != right[i].length)
            {
                return false;
            }
            for (int j = left[i].length - 1; j >= 0; j--)
            {
                result &= ByteUtils.equals(left[i][j], right[i][j]);
            }
        }

        return result;
    }

    /**
     * Computes a hashcode based on the contents of a one-dimensional byte array
     * rather than its identity.
     *
     * @param array the array to compute the hashcode of
     * @return the hashcode
     */
    public static int deepHashCode(byte[] array)
    {
        int result = 1;
        for (int i = 0; i < array.length; i++)
        {
            result = 31 * result + array[i];
        }
        return result;
    }

    /**
     * Computes a hashcode based on the contents of a two-dimensional byte array
     * rather than its identity.
     *
     * @param array the array to compute the hashcode of
     * @return the hashcode
     */
    public static int deepHashCode(byte[][] array)
    {
        int result = 1;
        for (int i = 0; i < array.length; i++)
        {
            result = 31 * result + deepHashCode(array[i]);
        }
        return result;
    }

    /**
     * Computes a hashcode based on the contents of a three-dimensional byte
     * array rather than its identity.
     *
     * @param array the array to compute the hashcode of
     * @return the hashcode
     */
    public static int deepHashCode(byte[][][] array)
    {
        int result = 1;
        for (int i = 0; i < array.length; i++)
        {
            result = 31 * result + deepHashCode(array[i]);
        }
        return result;
    }


    /**
     * Return a clone of the given byte array (performs null check beforehand).
     *
     * @param array the array to clone
     * @return the clone of the given array, or <tt>null</tt> if the array is
     *         <tt>null</tt>
     */
    public static byte[] clone(byte[] array)
    {
        if (array == null)
        {
            return null;
        }
        byte[] result = new byte[array.length];
        System.arraycopy(array, 0, result, 0, array.length);
        return result;
    }

    /**
     * Convert a string containing hexadecimal characters to a byte-array.
     *
     * @param s a hex string
     * @return a byte array with the corresponding value
     */
    public static byte[] fromHexString(String s)
    {
        char[] rawChars = s.toUpperCase().toCharArray();

        int hexChars = 0;
        for (int i = 0; i < rawChars.length; i++)
        {
            if ((rawChars[i] >= '0' && rawChars[i] <= '9')
                || (rawChars[i] >= 'A' && rawChars[i] <= 'F'))
            {
                hexChars++;
            }
        }

        byte[] byteString = new byte[(hexChars + 1) >> 1];

        int pos = hexChars & 1;

        for (int i = 0; i < rawChars.length; i++)
        {
            if (rawChars[i] >= '0' && rawChars[i] <= '9')
            {
                byteString[pos >> 1] <<= 4;
                byteString[pos >> 1] |= rawChars[i] - '0';
            }
            else if (rawChars[i] >= 'A' && rawChars[i] <= 'F')
            {
                byteString[pos >> 1] <<= 4;
                byteString[pos >> 1] |= rawChars[i] - 'A' + 10;
            }
            else
            {
                continue;
            }
            pos++;
        }

        return byteString;
    }

    /**
     * Convert a byte array to the corresponding hexstring.
     *
     * @param input the byte array to be converted
     * @return the corresponding hexstring
     */
    public static String toHexString(byte[] input)
    {
        String result = "";
        for (int i = 0; i < input.length; i++)
        {
            result += HEX_CHARS[(input[i] >>> 4) & 0x0f];
            result += HEX_CHARS[(input[i]) & 0x0f];
        }
        return result;
    }

    /**
     * Convert a byte array to the corresponding hex string.
     *
     * @param input     the byte array to be converted
     * @param prefix    the prefix to put at the beginning of the hex string
     * @param seperator a separator string
     * @return the corresponding hex string
     */
    public static String toHexString(byte[] input, String prefix,
                                     String seperator)
    {
        String result = new String(prefix);
        for (int i = 0; i < input.length; i++)
        {
            result += HEX_CHARS[(input[i] >>> 4) & 0x0f];
            result += HEX_CHARS[(input[i]) & 0x0f];
            if (i < input.length - 1)
            {
                result += seperator;
            }
        }
        return result;
    }

    /**
     * Convert a byte array to the corresponding bit string.
     *
     * @param input the byte array to be converted
     * @return the corresponding bit string
     */
    public static String toBinaryString(byte[] input)
    {
        String result = "";
        int i;
        for (i = 0; i < input.length; i++)
        {
            int e = input[i];
            for (int ii = 0; ii < 8; ii++)
            {
                int b = (e >>> ii) & 1;
                result += b;
            }
            if (i != input.length - 1)
            {
                result += " ";
            }
        }
        return result;
    }

    /**
     * Compute the bitwise XOR of two arrays of bytes. The arrays have to be of
     * same length. No length checking is performed.
     *
     * @param x1 the first array
     * @param x2 the second array
     * @return x1 XOR x2
     */
    public static byte[] xor(byte[] x1, byte[] x2)
    {
        byte[] out = new byte[x1.length];

        for (int i = x1.length - 1; i >= 0; i--)
        {
            out[i] = (byte)(x1[i] ^ x2[i]);
        }
        return out;
    }

    /**
     * Concatenate two byte arrays. No null checks are performed.
     *
     * @param x1 the first array
     * @param x2 the second array
     * @return (x2||x1) (little-endian order, i.e. x1 is at lower memory
     *         addresses)
     */
    public static byte[] concatenate(byte[] x1, byte[] x2)
    {
        byte[] result = new byte[x1.length + x2.length];

        System.arraycopy(x1, 0, result, 0, x1.length);
        System.arraycopy(x2, 0, result, x1.length, x2.length);

        return result;
    }

    /**
     * Convert a 2-dimensional byte array into a 1-dimensional byte array by
     * concatenating all entries.
     *
     * @param array a 2-dimensional byte array
     * @return the concatenated input array
     */
    public static byte[] concatenate(byte[][] array)
    {
        int rowLength = array[0].length;
        byte[] result = new byte[array.length * rowLength];
        int index = 0;
        for (int i = 0; i < array.length; i++)
        {
            System.arraycopy(array[i], 0, result, index, rowLength);
            index += rowLength;
        }
        return result;
    }

    /**
     * Split a byte array <tt>input</tt> into two arrays at <tt>index</tt>,
     * i.e. the first array will have the lower <tt>index</tt> bytes, the
     * second one the higher <tt>input.length - index</tt> bytes.
     *
     * @param input the byte array to be split
     * @param index the index where the byte array is split
     * @return the splitted input array as an array of two byte arrays
     * @throws ArrayIndexOutOfBoundsException if <tt>index</tt> is out of bounds
     */
    public static byte[][] split(byte[] input, int index)
        throws ArrayIndexOutOfBoundsException
    {
        if (index > input.length)
        {
            throw new ArrayIndexOutOfBoundsException();
        }
        byte[][] result = new byte[2][];
        result[0] = new byte[index];
        result[1] = new byte[input.length - index];
        System.arraycopy(input, 0, result[0], 0, index);
        System.arraycopy(input, index, result[1], 0, input.length - index);
        return result;
    }

    /**
     * Generate a subarray of a given byte array.
     *
     * @param input the input byte array
     * @param start the start index
     * @param end   the end index
     * @return a subarray of <tt>input</tt>, ranging from <tt>start</tt>
     *         (inclusively) to <tt>end</tt> (exclusively)
     */
    public static byte[] subArray(byte[] input, int start, int end)
    {
        byte[] result = new byte[end - start];
        System.arraycopy(input, start, result, 0, end - start);
        return result;
    }

    /**
     * Generate a subarray of a given byte array.
     *
     * @param input the input byte array
     * @param start the start index
     * @return a subarray of <tt>input</tt>, ranging from <tt>start</tt> to
     *         the end of the array
     */
    public static byte[] subArray(byte[] input, int start)
    {
        return subArray(input, start, input.length);
    }

    /**
     * Rewrite a byte array as a char array
     *
     * @param input -
     *              the byte array
     * @return char array
     */
    public static char[] toCharArray(byte[] input)
    {
        char[] result = new char[input.length];
        for (int i = 0; i < input.length; i++)
        {
            result[i] = (char)input[i];
        }
        return result;
    }

}