Search code examples
keyboardhexhidkeycode

List of hex keyboard scan codes and USB HID keyboard documentation


Where am I able to find a list of the hex keyboard scan codes for different keyboard layouts?

I'm sending the key codes over a (fake) USB HID keyboard with the bash command echo -ne followed by the escaped hex key scan code and the HID device:

echo -ne "\x00\x00\x00\x38\x00\x00\x00\x00" > /dev/hidg0
echo -ne "\x00\x00\x00\x00\x00\x00\x00\x00"  > /dev/hidg0

for a slash (/) on the US keyboard layout.

On my keyboard layout (CH) it is

echo -ne "\x00\x00\x00\x24\x00\x00\x00\x00" > /dev/hidg0
echo -ne "\x00\x00\x00\x00\x00\x00\x00\x00"  > /dev/hidg0

for a slash. So I guess there has to exist a list for all of these. Yet I was able to find a list for the US layout but not for any other keyboard layout.

I know the second line stops the typing of the key but I don't quite understand the syntax of these escape sequences. I know that if I change the first \x00 to a x02 it will "shift" the entered key. But why are there 6 more modifiers? Do they stand for ctrl, alt, ... ? And which stands for which?

A documentation of this syntax would be really cool. I wasn't able to find one yet.

(I'm using Kali Nethunter on a Nexus 7 2012)


Solution

  • The "scan codes" (they are really indexes to usage codes) are published on usb.org in the USB HID Usage Tables specification in Chapter 10 "Keyboard/Keypad Page (0x07)". A typical keyboard report layout can be found in the USB Device Class Specification for HID in Appendix B "Boot Interface Descriptors", section "B.1 Protocol 1 (Keyboard)".

    That describes the keyboard report format as:

    Byte 0: Keyboard modifier bits (SHIFT, ALT, CTRL etc)
    Byte 1: reserved
    Byte 2-7: Up to six keyboard usage indexes representing the keys that are 
              currently "pressed". 
              Order is not important, a key is either pressed (present in the 
              buffer) or not pressed.
    

    Note that the USB spec doesn't define keyboard layouts. It simply lists the usage codes assigned to particular key functions. The letter "a" is usage code 0x04 for example. If you want an uppercase "A", then you would also need to set the Byte 0 modifier bits to select "Left Shift" (or "Right Shift").

    The exact format of the report buffer depends on the Report Descriptor sent to the host computer when the keyboard was plugged in to a USB port, so the above is just a (pretty typical) example.