|
| 1 | +package io.github.hapjava.server.impl.crypto; |
| 2 | + |
| 3 | +import java.util.Base64; |
| 4 | +import org.bouncycastle.crypto.Digest; |
| 5 | +import org.bouncycastle.crypto.digests.SHA512Digest; |
| 6 | + |
| 7 | +public class HAPSetupCodeUtils { |
| 8 | + private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| 9 | + |
| 10 | + public static String randomAlphaNumeric(int count) { |
| 11 | + StringBuilder builder = new StringBuilder(); |
| 12 | + while (count-- != 0) { |
| 13 | + int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length()); |
| 14 | + builder.append(ALPHA_NUMERIC_STRING.charAt(character)); |
| 15 | + } |
| 16 | + return builder.toString(); |
| 17 | + } |
| 18 | + |
| 19 | + public static String generateSetupId() { |
| 20 | + return randomAlphaNumeric(4); |
| 21 | + } |
| 22 | + |
| 23 | + private static byte[] calculateHash(final String input, final Digest digest) { |
| 24 | + byte[] inputAsBytes = input.getBytes(); |
| 25 | + byte[] retValue = new byte[digest.getDigestSize()]; |
| 26 | + digest.update(inputAsBytes, 0, inputAsBytes.length); |
| 27 | + digest.doFinal(retValue, 0); |
| 28 | + return retValue; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * generate SHA52 Hash for given string. The hash is used for mDNS advertisement. |
| 33 | + * |
| 34 | + * @param value value |
| 35 | + * @return hash |
| 36 | + */ |
| 37 | + public static String generateSHA512Hash(final String value) { |
| 38 | + final byte[] hash = calculateHash(value.toUpperCase(), new SHA512Digest()); |
| 39 | + final byte[] hashTuncate = new byte[4]; |
| 40 | + System.arraycopy(hash, 0, hashTuncate, 0, 4); |
| 41 | + String hashStr = Base64.getEncoder().encodeToString(hashTuncate); |
| 42 | + return hashStr; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * generate Setup URI which can be used fo QR Code generation. |
| 47 | + * |
| 48 | + * @param pin PIN number without "-" |
| 49 | + * @param setupId alphanumeric string of the length 4 |
| 50 | + * @param category accessory category |
| 51 | + * @return setup UID |
| 52 | + */ |
| 53 | + public static String getSetupURI(final String pin, final String setupId, final int category) { |
| 54 | + long code = |
| 55 | + 0 << 43 // Version |
| 56 | + | 0 << 39 // Reserved |
| 57 | + | ((long) category) << 31 // Category |
| 58 | + | 0 << 29 // BLE support |
| 59 | + | 1 << 28 // IP support |
| 60 | + | 0 << 27 // Paired / NFC |
| 61 | + | Integer.valueOf(pin); // PIN |
| 62 | + String payload = Long.toString(code, 36) + setupId; |
| 63 | + while (payload.length() < 13) { |
| 64 | + payload = '0' + payload; |
| 65 | + } |
| 66 | + return "X-HM://" + payload.toUpperCase(); |
| 67 | + } |
| 68 | +} |
0 commit comments