imgtool: Add public key's SHA256 hash calculation

Signed-off-by: Dávid Házi <david.hazi@arm.com>
Signed-off-by: Bence Balogh <bence.balogh@arm.com>
Change-Id: I91d5c07c1bb2b8abe2592cd49b2053c881465ba2
diff --git a/scripts/imgtool/keys/general.py b/scripts/imgtool/keys/general.py
index 45cddc6..b415f47 100644
--- a/scripts/imgtool/keys/general.py
+++ b/scripts/imgtool/keys/general.py
@@ -3,6 +3,7 @@
 # SPDX-License-Identifier: Apache-2.0
 
 import sys
+from cryptography.hazmat.primitives.hashes import Hash, SHA256
 
 AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"
 
@@ -34,11 +35,26 @@
 
     def emit_c_public(self, file=sys.stdout):
         self._emit(
-                header="const unsigned char {}_pub_key[] = {{".format(self.shortname()),
+                header="const unsigned char {}_pub_key[] = {{"
+                       .format(self.shortname()),
                 trailer="};",
                 encoded_bytes=self.get_public_bytes(),
                 indent="    ",
-                len_format="const unsigned int {}_pub_key_len = {{}};".format(self.shortname()),
+                len_format="const unsigned int {}_pub_key_len = {{}};"
+                           .format(self.shortname()),
+                file=file)
+
+    def emit_c_public_hash(self, file=sys.stdout):
+        digest = Hash(SHA256())
+        digest.update(self.get_public_bytes())
+        self._emit(
+                header="const unsigned char {}_pub_key_hash[] = {{"
+                       .format(self.shortname()),
+                trailer="};",
+                encoded_bytes=digest.finalize(),
+                indent="    ",
+                len_format="const unsigned int {}_pub_key_hash_len = {{}};"
+                           .format(self.shortname()),
                 file=file)
 
     def emit_raw_public(self, file=sys.stdout):
@@ -48,9 +64,19 @@
         else:
             sys.stdout.buffer.write(self.get_public_bytes())
 
+    def emit_raw_public_hash(self, file=sys.stdout):
+        digest = Hash(SHA256())
+        digest.update(self.get_public_bytes())
+        if file and file is not sys.stdout:
+            with open(file, 'wb') as file:
+                file.write(digest.finalize())
+        else:
+            sys.stdout.buffer.write(digest.finalize())
+
     def emit_rust_public(self, file=sys.stdout):
         self._emit(
-                header="static {}_PUB_KEY: &[u8] = &[".format(self.shortname().upper()),
+                header="static {}_PUB_KEY: &[u8] = &["
+                       .format(self.shortname().upper()),
                 trailer="];",
                 encoded_bytes=self.get_public_bytes(),
                 indent="    ",