Skip to content

Commit a116c99

Browse files
committed
Add function to generate device hash from QR code
1 parent bdb7643 commit a116c99

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

HomeKitDotNet/QRParser.cs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,27 @@
1-
namespace HomeKitDotNet
1+
// HomeKitDotNet Copyright (C) 2024
2+
//
3+
// This program is free software: you can redistribute it and/or modify
4+
// it under the terms of the GNU Affero General Public License as published by
5+
// the Free Software Foundation, either version 3 of the License, or any later version.
6+
// This program is distributed in the hope that it will be useful,
7+
// but WITHOUT ANY WARRANTY, without even the implied warranty of
8+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9+
// See the GNU Affero General Public License for more details.
10+
// You should have received a copy of the GNU Affero General Public License
11+
// along with this program. If not, see <http://www.gnu.org/licenses/>.
12+
13+
using System.Security.Cryptography;
14+
using System.Text;
15+
16+
namespace HomeKitDotNet
217
{
318
public class QRParser
419
{
520
public QRParser(string code)
621
{
7-
if (!code.StartsWith("X-HM://") || code.Length != 20)
22+
if (!code.StartsWith("X-HM://") || code.Length < 20)
823
throw new ArgumentException("Invalid QR Code");
9-
SetupCode = code.Substring(16);
24+
SetupID = code.Substring(16, 4);
1025
code = code.Substring(7, 9);
1126
long lc = decode(code);
1227
Version = (byte)((lc >> 43) & 0xFF);
@@ -22,9 +37,19 @@ public QRParser(string code)
2237
public bool BTLE { get; set; }
2338
public bool NFC { get; set; }
2439
public bool IP { get; set; }
25-
public string SetupCode { get; set; }
40+
public string SetupID { get; set; }
2641
public long SetupPin { get; set; }
2742

43+
public string ComputeHash(string deviceId)
44+
{
45+
byte[] devId = Encoding.UTF8.GetBytes(deviceId.ToUpper());
46+
byte[] source = new byte[devId.Length + 4];
47+
Encoding.UTF8.GetBytes(SetupID, 0, 4, source, 0);
48+
Array.Copy(devId, 0, source, 4, devId.Length);
49+
byte[] result = SHA512.HashData(source);
50+
return Convert.ToHexString(result, 0, 4);
51+
}
52+
2853
private static long decode(string sIn)
2954
{
3055
const string map = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

0 commit comments

Comments
 (0)