Add ed25519 signing support to imgtool

This adds ed25519 signature support using the "prehash" method. Instead
of using the direct contents of the image and header payloads, a sha256
is generated and signed (SHA256-Ed25519). This allows for compatibility
with already existing tools that use the sha256 hash, like mcumgr, etc.

Signed-off-by: Fabio Utzig <utzig@apache.org>
diff --git a/scripts/imgtool/image.py b/scripts/imgtool/image.py
index 20f8e75..9bb4801 100644
--- a/scripts/imgtool/image.py
+++ b/scripts/imgtool/image.py
@@ -52,6 +52,7 @@
         'ECDSA224': 0x21,
         'ECDSA256': 0x22,
         'RSA3072': 0x23,
+        'ED25519': 0x24,
         'ENCRSA2048': 0x30,
         'ENCKW128': 0x31,
         'DEPENDENCY': 0x40
@@ -241,7 +242,13 @@
             pubbytes = sha.digest()
             tlv.add('KEYHASH', pubbytes)
 
-            sig = key.sign(bytes(self.payload))
+            # `sign` expects the full image payload (sha256 done internally),
+            # while `sign_digest` expects only the digest of the payload
+
+            if hasattr(key, 'sign'):
+                sig = key.sign(bytes(self.payload))
+            else:
+                sig = key.sign_digest(digest)
             tlv.add(key.sig_tlv(), sig)
 
         if enckey is not None:
@@ -354,7 +361,10 @@
                 tlv_sig = b[off:off+tlv_len]
                 payload = b[:header_size+img_size]
                 try:
-                    key.verify(tlv_sig, payload)
+                    if hasattr(key, 'verify'):
+                        key.verify(tlv_sig, payload)
+                    else:
+                        key.verify_digest(tlv_sig, digest)
                     return VerifyResult.OK
                 except InvalidSignature:
                     # continue to next TLV
diff --git a/scripts/imgtool/keys/__init__.py b/scripts/imgtool/keys/__init__.py
index b92f871..1145735 100644
--- a/scripts/imgtool/keys/__init__.py
+++ b/scripts/imgtool/keys/__init__.py
@@ -20,9 +20,11 @@
 from cryptography.hazmat.primitives import serialization
 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
 from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
 
 from .rsa import RSA, RSAPublic, RSAUsageError, RSA_KEY_SIZES
 from .ecdsa import ECDSA256P1, ECDSA256P1Public, ECDSAUsageError
+from .ed25519 import Ed25519, Ed25519Public, Ed25519UsageError
 
 class PasswordRequired(Exception):
     """Raised to indicate that the key is password protected, but a
@@ -72,5 +74,9 @@
         if pk.key_size != 256:
             raise Exception("Unsupported EC size: " + pk.key_size)
         return ECDSA256P1Public(pk)
+    elif isinstance(pk, Ed25519PrivateKey):
+        return Ed25519(pk)
+    elif isinstance(pk, Ed25519PublicKey):
+        return Ed25519Public(pk)
     else:
         raise Exception("Unknown key type: " + str(type(pk)))
diff --git a/scripts/imgtool/keys/ed25519.py b/scripts/imgtool/keys/ed25519.py
new file mode 100644
index 0000000..57eb99a
--- /dev/null
+++ b/scripts/imgtool/keys/ed25519.py
@@ -0,0 +1,98 @@
+"""
+ECDSA key management
+"""
+
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ed25519
+
+from .general import KeyClass
+
+
+class Ed25519UsageError(Exception):
+    pass
+
+
+class Ed25519Public(KeyClass):
+    def __init__(self, key):
+        self.key = key
+
+    def shortname(self):
+        return "ed25519"
+
+    def _unsupported(self, name):
+        raise Ed25519UsageError("Operation {} requires private key".format(name))
+
+    def _get_public(self):
+        return self.key
+
+    def get_public_bytes(self):
+        # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
+        return self._get_public().public_bytes(
+                encoding=serialization.Encoding.DER,
+                format=serialization.PublicFormat.SubjectPublicKeyInfo)
+
+    def export_private(self, path, passwd=None):
+        self._unsupported('export_private')
+
+    def export_public(self, path):
+        """Write the public key to the given file."""
+        pem = self._get_public().public_bytes(
+                encoding=serialization.Encoding.PEM,
+                format=serialization.PublicFormat.SubjectPublicKeyInfo)
+        with open(path, 'wb') as f:
+            f.write(pem)
+
+    def sig_type(self):
+        return "ED25519"
+
+    def sig_tlv(self):
+        return "ED25519"
+
+    def sig_len(self):
+        return 64
+
+
+class Ed25519(Ed25519Public):
+    """
+    Wrapper around an ECDSA private key.
+    """
+
+    def __init__(self, key):
+        """key should be an instance of EllipticCurvePrivateKey"""
+        self.key = key
+
+    @staticmethod
+    def generate():
+        pk = ed25519.Ed25519PrivateKey.generate()
+        return Ed25519(pk)
+
+    def _get_public(self):
+        return self.key.public_key()
+
+    def export_private(self, path, passwd=None):
+        """
+        Write the private key to the given file, protecting it with the
+        optional password.
+        """
+        if passwd is None:
+            enc = serialization.NoEncryption()
+        else:
+            enc = serialization.BestAvailableEncryption(passwd)
+        pem = self.key.private_bytes(
+                encoding=serialization.Encoding.PEM,
+                format=serialization.PrivateFormat.PKCS8,
+                encryption_algorithm=enc)
+        with open(path, 'wb') as f:
+            f.write(pem)
+
+    def sign_digest(self, digest):
+        """Return the actual signature"""
+        return self.key.sign(data=digest)
+
+    def verify_digest(self, signature, digest):
+        """Verify that signature is valid for given digest"""
+        k = self.key
+        if isinstance(self.key, ed25519.Ed25519PrivateKey):
+            k = self.key.public_key()
+        return k.verify(signature=signature, data=digest)
diff --git a/scripts/imgtool/keys/ed25519_test.py b/scripts/imgtool/keys/ed25519_test.py
new file mode 100644
index 0000000..6ed3656
--- /dev/null
+++ b/scripts/imgtool/keys/ed25519_test.py
@@ -0,0 +1,96 @@
+"""
+Tests for ECDSA keys
+"""
+
+import io
+import os.path
+import sys
+import tempfile
+import unittest
+
+from cryptography.exceptions import InvalidSignature
+from cryptography.hazmat.primitives.asymmetric import ed25519
+
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
+
+from imgtool.keys import load, Ed25519, Ed25519UsageError
+
+
+class Ed25519KeyGeneration(unittest.TestCase):
+
+    def setUp(self):
+        self.test_dir = tempfile.TemporaryDirectory()
+
+    def tname(self, base):
+        return os.path.join(self.test_dir.name, base)
+
+    def tearDown(self):
+        self.test_dir.cleanup()
+
+    def test_keygen(self):
+        name1 = self.tname("keygen.pem")
+        k = Ed25519.generate()
+        k.export_private(name1, b'secret')
+
+        self.assertIsNone(load(name1))
+
+        k2 = load(name1, b'secret')
+
+        pubname = self.tname('keygen-pub.pem')
+        k2.export_public(pubname)
+        pk2 = load(pubname)
+
+        # We should be able to export the public key from the loaded
+        # public key, but not the private key.
+        pk2.export_public(self.tname('keygen-pub2.pem'))
+        self.assertRaises(Ed25519UsageError,
+                          pk2.export_private, self.tname('keygen-priv2.pem'))
+
+    def test_emit(self):
+        """Basic sanity check on the code emitters."""
+        k = Ed25519.generate()
+
+        ccode = io.StringIO()
+        k.emit_c(ccode)
+        self.assertIn("ed25519_pub_key", ccode.getvalue())
+        self.assertIn("ed25519_pub_key_len", ccode.getvalue())
+
+        rustcode = io.StringIO()
+        k.emit_rust(rustcode)
+        self.assertIn("ED25519_PUB_KEY", rustcode.getvalue())
+
+    def test_emit_pub(self):
+        """Basic sanity check on the code emitters."""
+        pubname = self.tname("public.pem")
+        k = Ed25519.generate()
+        k.export_public(pubname)
+
+        k2 = load(pubname)
+
+        ccode = io.StringIO()
+        k2.emit_c(ccode)
+        self.assertIn("ed25519_pub_key", ccode.getvalue())
+        self.assertIn("ed25519_pub_key_len", ccode.getvalue())
+
+        rustcode = io.StringIO()
+        k2.emit_rust(rustcode)
+        self.assertIn("ED25519_PUB_KEY", rustcode.getvalue())
+
+    def test_sig(self):
+        k = Ed25519.generate()
+        buf = b'This is the message'
+        sig = k.raw_sign(buf)
+
+        # The code doesn't have any verification, so verify this
+        # manually.
+        k.key.public_key().verify(signature=sig, data=buf)
+
+        # Modify the message to make sure the signature fails.
+        self.assertRaises(InvalidSignature,
+                          k.key.public_key().verify,
+                          signature=sig,
+                          data=b'This is thE message')
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/scripts/imgtool/main.py b/scripts/imgtool/main.py
index 476884c..0a8fe0d 100755
--- a/scripts/imgtool/main.py
+++ b/scripts/imgtool/main.py
@@ -41,12 +41,17 @@
     print("TODO: p-224 not yet implemented")
 
 
+def gen_ed25519(keyfile, passwd):
+    keys.Ed25519.generate().export_private(path=keyfile)
+
+
 valid_langs = ['c', 'rust']
 keygens = {
     'rsa-2048':   gen_rsa2048,
     'rsa-3072':   gen_rsa3072,
     'ecdsa-p256': gen_ecdsa_p256,
     'ecdsa-p224': gen_ecdsa_p224,
+    'ed25519': gen_ed25519,
 }