| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.content.integrity; |
| 18 |
|
| 19 |
import static com.android.internal.util.Preconditions.checkArgument; |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
public class IntegrityUtils { |
| 27 |
|
| 28 |
private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray(); |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
public static byte[] getBytesFromHexDigest(String hexDigest) { |
| 37 |
checkArgument( |
| 38 |
hexDigest.length() % 2 == 0, |
| 39 |
"Invalid hex encoding %s: must have even length", hexDigest); |
| 40 |
|
| 41 |
byte[] rawBytes = new byte[hexDigest.length() / 2]; |
| 42 |
for (int i = 0; i < rawBytes.length; i++) { |
| 43 |
int upperNibble = hexDigest.charAt(2 * i); |
| 44 |
int lowerNibble = hexDigest.charAt(2 * i + 1); |
| 45 |
rawBytes[i] = (byte) ((hexToDec(upperNibble) << 4) | hexToDec(lowerNibble)); |
| 46 |
} |
| 47 |
return rawBytes; |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
public static String getHexDigest(byte[] rawBytes) { |
| 52 |
char[] hexChars = new char[rawBytes.length * 2]; |
| 53 |
|
| 54 |
for (int i = 0; i < rawBytes.length; i++) { |
| 55 |
int upperNibble = (rawBytes[i] >>> 4) & 0xF; |
| 56 |
int lowerNibble = rawBytes[i] & 0xF; |
| 57 |
hexChars[i * 2] = decToHex(upperNibble); |
| 58 |
hexChars[i * 2 + 1] = decToHex(lowerNibble); |
| 59 |
} |
| 60 |
return new String(hexChars); |
| 61 |
} |
| 62 |
|
| 63 |
private static int hexToDec(int hexChar) { |
| 64 |
if (hexChar >= '0' && hexChar <= '9') { |
| 65 |
return hexChar - '0'; |
| 66 |
} |
| 67 |
if (hexChar >= 'a' && hexChar <= 'f') { |
| 68 |
return hexChar - 'a' + 10; |
| 69 |
} |
| 70 |
if (hexChar >= 'A' && hexChar <= 'F') { |
| 71 |
return hexChar - 'A' + 10; |
| 72 |
} |
| 73 |
throw new IllegalArgumentException("Invalid hex char " + hexChar); |
| 74 |
} |
| 75 |
|
| 76 |
private static char decToHex(int dec) { |
| 77 |
if (dec >= 0 && dec < HEX_CHARS.length) { |
| 78 |
return HEX_CHARS[dec]; |
| 79 |
} |
| 80 |
|
| 81 |
throw new IllegalArgumentException("Invalid dec value to be converted to hex digit " + dec); |
| 82 |
} |
| 83 |
} |