Move key_id from header into TLV

Remove the key_id field from the image header.  There are two problems
with this field.  First, it is only an integer offset, and so causes an
unnecessarily tight coupling between the particular keys built into the
bootloader, and the key that is used to sign.  Second, it makes the
key_id part of the image header, which is included in the signature.
This makes it impossible to later sign the image with a different
signature.

Instead of the key-id, add a TLV KEYHASH entry.  This will hold the
SHA256 of the public key that the signature is against.  Each signature
placed in the TLV should be preceeded by this entry to indicate the
public key used.

The signature check will check each signature, and if the KEYHASH is
known and the signature type is supported, it will be checked.  As long
as at least one signature is considered valid, the image will be
considered signed.  This also allows the image to be signed with
multiple signatures to support having different devices with possibly
different keys compiled into the bootloaders.

Based on work by Marko Kiiskila <marko@runtime.io>

Signed-off-by: Marko Kiiskila <marko@runtime.io>
Signed-off-by: David Brown <david.brown@linaro.org>
diff --git a/scripts/imgtool/image.py b/scripts/imgtool/image.py
index cd031be..9a9225f 100644
--- a/scripts/imgtool/image.py
+++ b/scripts/imgtool/image.py
@@ -12,14 +12,10 @@
 # Image header flags.
 IMAGE_F = {
         'PIC':                   0x0000001,
-        'SHA256':                0x0000002,
-        'PKCS15_RSA2048_SHA256': 0x0000004,
-        'ECDSA224_SHA256':       0x0000008,
-        'NON_BOOTABLE':          0x0000010,
-        'ECDSA256_SHA256':       0x0000020,
-        'PKCS1_PSS_RSA2048_SHA256': 0x0000040, }
+        'NON_BOOTABLE':          0x0000010, }
 
 TLV_VALUES = {
+        'KEYHASH': 0x01,
         'SHA256': 0x10,
         'RSA2048': 0x20,
         'ECDSA224': 0x21,
@@ -106,6 +102,12 @@
         tlv.add('SHA256', digest)
 
         if key is not None:
+            pub = key.get_public_bytes()
+            sha = hashlib.sha256()
+            sha.update(pub)
+            pubbytes = sha.digest()
+            tlv.add('KEYHASH', pubbytes)
+
             sig = key.sign(self.payload)
             tlv.add(key.sig_tlv(), sig)
 
@@ -120,10 +122,9 @@
         flags = 0
         tlvsz = 0
         if key is not None:
-            flags |= IMAGE_F[key.sig_type()]
             tlvsz += TLV_HEADER_SIZE + key.sig_len()
 
-        flags |= IMAGE_F['SHA256']
+        tlvsz += 4 + hashlib.sha256().digest_size
         tlvsz += 4 + hashlib.sha256().digest_size
 
         fmt = ('<' +