Debian Codegraph @

ext/ed25519_jruby/net/i2p/crypto/eddsa/Utils.java

raw symbols SCIP
1 /**
2 * EdDSA-Java by str4d
3 *
4 * To the extent possible under law, the person who associated CC0 with
5 * EdDSA-Java has waived all copyright and related or neighboring rights
6 * to EdDSA-Java.
7 *
8 * You should have received a copy of the CC0 legalcode along with this
9 * work. If not, see <https://creativecommons.org/publicdomain/zero/1.0/>.
10 *
11 */
12 package net.i2p.crypto.eddsa;
13
14 /**
15 * Basic utilities for EdDSA.
16 * Not for external use, not maintained as a public API.
17 *
18 * @author str4d
19 *
20 */
21 public class Utils {
22 /**
23 * Constant-time byte comparison.
24 * @param b a byte
25 * @param c a byte
26 * @return 1 if b and c are equal, 0 otherwise.
27 */
28 public static int equal(int b, int c) {
29 int result = 0;
30 int xor = b ^ c;
31 for (int i = 0; i < 8; i++) {
32 result |= xor >> i;
33 }
34 return (result ^ 0x01) & 0x01;
35 }
36
37 /**
38 * Constant-time byte[] comparison.
39 * @param b a byte[]
40 * @param c a byte[]
41 * @return 1 if b and c are equal, 0 otherwise.
42 */
43 public static int equal(byte[] b, byte[] c) {
44 int result = 0;
45 for (int i = 0; i < 32; i++) {
46 result |= b[i] ^ c[i];
47 }
48
49 return equal(result, 0);
50 }
51
52 /**
53 * Constant-time determine if byte is negative.
54 * @param b the byte to check.
55 * @return 1 if the byte is negative, 0 otherwise.
56 */
57 public static int negative(int b) {
58 return (b >> 8) & 1;
59 }
60
61 /**
62 * Get the i'th bit of a byte array.
63 * @param h the byte array.
64 * @param i the bit index.
65 * @return 0 or 1, the value of the i'th bit in h
66 */
67 public static int bit(byte[] h, int i) {
68 return (h[i >> 3] >> (i & 7)) & 1;
69 }
70
71 /**
72 * Converts a hex string to bytes.
73 * @param s the hex string to be converted.
74 * @return the byte[]
75 */
76 public static byte[] hexToBytes(String s) {
77 int len = s.length();
78 byte[] data = new byte[len / 2];
79 for (int i = 0; i < len; i += 2) {
80 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
81 + Character.digit(s.charAt(i+1), 16));
82 }
83 return data;
84 }
85
86 /**
87 * Converts bytes to a hex string.
88 * @param raw the byte[] to be converted.
89 * @return the hex representation as a string.
90 */
91 public static String bytesToHex(byte[] raw) {
92 if ( raw == null ) {
93 return null;
94 }
95 final StringBuilder hex = new StringBuilder(2 * raw.length);
96 for (final byte b : raw) {
97 hex.append(Character.forDigit((b & 0xF0) >> 4, 16))
98 .append(Character.forDigit((b & 0x0F), 16));
99 }
100 return hex.toString();
101 }
102
103 }