silitics / rpi-derive-key

A utility for deriving secure device-specific keys on Raspberry Pi.
Apache License 2.0
2 stars 0 forks source link

Python examples #1

Open 3goats opened 3 months ago

3goats commented 3 months ago

Hi,

Thanks for this utility. I can't seem to work out how to use the python libraries for this.

I have this working on my Pi:

$rpi-derive-key uuid 123
8eff8b78-4a64-42ad-a8f3-b887cf5f828b

However, I need to get the value using python. Do you have some examples anywhere ?

koehlma commented 3 months ago

Hey, right now there are no examples. Something along the following lines should work:

deriver = rpi_dervice_key.DeriverBuilder().build()
key = deriver.derive_key(16, "123")

It will give you a sequence of 16 bytes that you can then use for a UUID.

3goats commented 3 months ago

Thanks for this - really helpful. So I have this code working:

import  rpi_derive_key
import uuid
deriver = rpi_derive_key.DeriverBuilder().build()
key = deriver.derive_key(16, "123")
dev_uuid = uuid.UUID(int=int.from_bytes(key))
print(dev_uuid)

Which outputs: 8eff8b78-4a64-02ad-68f3-b887cf5f828b

However this differs from the CLI (rpi-derive-key uuid "123") which outputs: 8eff8b78-4a64-42ad-a8f3-b887cf5f828b

Which is very close - Am I missing something here ?

koehlma commented 3 months ago

The derive_key method gives you a key of the specified length which you should treat as random bytes. To obtain a valid UUIDv4 (random generation) from these bytes, a few bits must be explicitly set/overwritten, see [1]. Generally, the third sequence should always start with a 4, indicating that it is a version 4 UUID. Whether generating a version 4 UUID is the correct thing, is something one could argue about. I would say that the bytes are pseudo-random, as they have been derived from a randomly generated key.

[1] https://datatracker.ietf.org/doc/html/rfc9562#name-uuid-version-4

3goats commented 3 months ago

Thanks - Changing this line in my code to this worked:

dev_uuid = uuid.UUID(int=int.from_bytes(key), version=4)

Just out of interest, how do you create the token in your CLI examples ? I need to do the same in Python.

koehlma commented 3 months ago

You mean the strings like device.id and device.secret.token? I just concatenated some things I felt sensible to a .-separated string. There is no deeper schema or mechanism. Also out of curiosity, may I ask, what are you building?

3goats commented 3 months ago

Yes exactly.

I'm looking at building out a sort of control plane for Pi devices that enables the management of X.509 assets. Essentially, I'm looking to use the random OTP bytes to attach an initial identity too.