+#include "hidcardformats.h"
+#include "hidcardformatutils.h"
+#include "util.h" // for param_get8,32,64
+
+
+/**
+ * Converts a hex string to component "hi2", "hi" and "lo" 32-bit integers, one nibble
+ * at a time.
+ *
+ * Returns the number of nibbles (4 bits) entered.
+ */
+int hexstring_to_int96(/* out */ uint32_t* hi2,/* out */ uint32_t* hi, /* out */ uint32_t* lo, const char* str) {
+ // TODO: Replace this with param_gethex when it supports arbitrary length
+ // inputs.
+ int n = 0, i = 0;
+
+ while (sscanf(&str[i++], "%1x", &n ) == 1) {
+ *hi2 = (*hi2 << 4) | (*hi >> 28);
+ *hi = (*hi << 4) | (*lo >> 28);
+ *lo = (*lo << 4) | (n & 0xf);
+ }
+
+ return i - 1;
+}
+
+void usage_encode(){
+ PrintAndLog("Usage: lf hid encode <format> [<field> <value (decimal)>] {...}");
+ PrintAndLog(" Fields: c: Card number");
+ PrintAndLog(" f: Facility code");
+ PrintAndLog(" i: Issue Level");
+ PrintAndLog(" o: OEM code");
+ PrintAndLog(" example: lf hid encode H10301 f 123 c 4567");
+}
+void PrintProxTagId(hidproxmessage_t *packed){
+ if (packed->top != 0) {
+ PrintAndLog("HID Prox TAG ID: %x%08x%08x",
+ (uint32_t)packed->top, (uint32_t)packed->mid, (uint32_t)packed->bot);
+ } else {
+ PrintAndLog("HID Prox TAG ID: %x%08x",
+ (uint32_t)packed->mid, (uint32_t)packed->bot);
+ }
+}
+bool Encode(/* in */ const char *Cmd, /* out */ hidproxmessage_t *packed){
+ int formatIndex = -1;
+ char format[16];
+ memset(format, 0, sizeof(format));
+ if (!strcmp(Cmd, "help") || !strcmp(Cmd, "h") || !strcmp(Cmd, "list") || !strcmp(Cmd, "?")){
+ usage_encode();
+ return false;
+ } else {
+ param_getstr(Cmd, 0, format, sizeof(format));
+ formatIndex = HIDFindCardFormat(format);
+ if (formatIndex == -1) {
+ printf("Unknown format: %s\r\n", format);
+ return false;
+ }
+ }
+ hidproxcard_t data;
+ memset(&data, 0, sizeof(hidproxcard_t));
+ uint8_t cmdp = 1;
+ while(param_getchar(Cmd, cmdp) != 0x00) {
+ switch(param_getchar(Cmd, cmdp)) {
+ case 'I':
+ case 'i':
+ data.IssueLevel = param_get32ex(Cmd, cmdp+1, 0, 10);
+ cmdp += 2;
+ break;
+ case 'F':
+ case 'f':
+ data.FacilityCode = param_get32ex(Cmd, cmdp+1, 0, 10);
+ cmdp += 2;
+ break;
+ case 'C':
+ case 'c':
+ data.CardNumber = param_get64ex(Cmd, cmdp+1, 0, 10);
+ cmdp += 2;
+ break;
+ case 'o':
+ case 'O':
+ data.OEM = param_get32ex(Cmd, cmdp+1, 0, 10);
+ cmdp += 2;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
+ return false;
+ }
+ }
+ memset(packed, 0, sizeof(hidproxmessage_t));
+ if (!HIDPack(formatIndex, &data, packed))
+ {
+ PrintAndLog("The card data could not be encoded in the selected format.");
+ return false;
+ } else {
+ return true;
+ }
+
+}
+void Write(hidproxmessage_t *packed){
+ UsbCommand c;
+ c.d.asBytes[0] = (packed->top != 0 && ((packed->mid & 0xFFFFFFC0) != 0))
+ ? 1 : 0; // Writing long format?
+ c.cmd = CMD_HID_CLONE_TAG;
+ c.arg[0] = (packed->top & 0x000FFFFF);
+ c.arg[1] = packed->mid;
+ c.arg[2] = packed->bot;
+ SendCommand(&c);
+}