Skip to content

Instantly share code, notes, and snippets.

@ssievert42
Created November 25, 2024 19:57
Show Gist options
  • Save ssievert42/dd979303b228cbd1c52733a3f63004cf to your computer and use it in GitHub Desktop.
Save ssievert42/dd979303b228cbd1c52733a3f63004cf to your computer and use it in GitHub Desktop.
crypto test: AES CCM BTHome advertisement
// crypto test for aes ccm, for (eventual) bthome encryption
// see: https://bthome.io/encryption
let macAddress = "5448E68F80A5";
let uuid = "d2fc";
let btHomeDeviceDataByte = "41"
let counter = "00112233";
let key = "231d39c1d7cc1ab1aee224cd096db932";
let data = "02CA0903BF13";
let nonce = macAddress + uuid + btHomeDeviceDataByte + counter;
print("nonce: " + nonce);
function hexStringToArrayBuffer(str) {
if (str.length % 2 != 0) {
return null;
}
let length = str.length / 2;
let buf = Uint8Array(length);
for (let i=0; i<length; i++) {
buf[i] = parseInt(str.slice(i * 2, i * 2 + 2), 16);
}
return buf;
}
function arrayBufferToHexString(buf) {
let str = "";
for (let i=0; i<buf.length; i++) {
str += buf[i].toString(16).padStart(2, '0');
}
return str;
}
let keyBuf = hexStringToArrayBuffer(key);
let iv = hexStringToArrayBuffer(nonce);
let dataBuf = hexStringToArrayBuffer(data);
let result = AES.ccmEncrypt(dataBuf, keyBuf, iv, 4);
let resultString = arrayBufferToHexString(result.data);
print("encrypted data: " + resultString);
let resultTagString = arrayBufferToHexString(result.tag);
print("tag: " + resultTagString);
let decryptResult = AES.ccmDecrypt(result.data, keyBuf, iv, result.tag);
let decryptResultString = arrayBufferToHexString(decryptResult);
print("decrypted: " + decryptResultString);
if (data.toLowerCase() == decryptResultString) {
print("success: unencrypted and decrypted data match!");
} else {
print("error: unencrypted and decrypted data don't match!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment