Boot: add original files from MCUBoot and Zephyr project

Aligned with MCUBoot version 1.0.0
MCUBoot files:
 -- bl2/ext/mcuboot

Aligned with Zephyr version 1.10.0
Zephyr files:
 -- bl2/ext/mcuboot/include/util.h
 -- platform/ext/target/common/flash.h

Change-Id: I314c3efa2bd2c13a4a2eaefeb5da43e53e988638
Signed-off-by: Tamas Ban <tamas.ban@arm.com>
diff --git a/bl2/ext/mcuboot/scripts/imgtool/keys.py b/bl2/ext/mcuboot/scripts/imgtool/keys.py
new file mode 100644
index 0000000..ee54a0f
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/keys.py
@@ -0,0 +1,183 @@
+# Copyright 2017 Linaro Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Cryptographic key management for imgtool.
+"""
+
+from Crypto.Hash import SHA256
+from Crypto.PublicKey import RSA
+from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS
+from ecdsa import SigningKey, NIST256p, util
+import hashlib
+from pyasn1.type import namedtype, univ
+from pyasn1.codec.der.encoder import encode
+
+# By default, we use RSA-PSS (PKCS 2.1).  That can be overridden on
+# the command line to support the older (less secure) PKCS1.5
+sign_rsa_pss = True
+
+AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"
+
+class RSAPublicKey(univ.Sequence):
+    componentType = namedtype.NamedTypes(
+            namedtype.NamedType('modulus', univ.Integer()),
+            namedtype.NamedType('publicExponent', univ.Integer()))
+
+class RSA2048():
+    def __init__(self, key):
+        """Construct an RSA2048 key with the given key data"""
+        self.key = key
+
+    @staticmethod
+    def generate():
+        return RSA2048(RSA.generate(2048))
+
+    def export_private(self, path):
+        with open(path, 'wb') as f:
+            f.write(self.key.exportKey('PEM'))
+
+    def get_public_bytes(self):
+        node = RSAPublicKey()
+        node['modulus'] = self.key.n
+        node['publicExponent'] = self.key.e
+        return bytearray(encode(node))
+
+    def emit_c(self):
+        print(AUTOGEN_MESSAGE)
+        print("const unsigned char rsa_pub_key[] = {", end='')
+        encoded = self.get_public_bytes()
+        for count, b in enumerate(encoded):
+            if count % 8 == 0:
+                print("\n\t", end='')
+            else:
+                print(" ", end='')
+            print("0x{:02x},".format(b), end='')
+        print("\n};")
+        print("const unsigned int rsa_pub_key_len = {};".format(len(encoded)))
+
+    def emit_rust(self):
+        print(AUTOGEN_MESSAGE)
+        print("static RSA_PUB_KEY: &'static [u8] = &[", end='')
+        encoded = self.get_public_bytes()
+        for count, b in enumerate(encoded):
+            if count % 8 == 0:
+                print("\n    ", end='')
+            else:
+                print(" ", end='')
+            print("0x{:02x},".format(b), end='')
+        print("\n];")
+
+    def sig_type(self):
+        """Return the type of this signature (as a string)"""
+        if sign_rsa_pss:
+            return "PKCS1_PSS_RSA2048_SHA256"
+        else:
+            return "PKCS15_RSA2048_SHA256"
+
+    def sig_len(self):
+        return 256
+
+    def sig_tlv(self):
+        return "RSA2048"
+
+    def sign(self, payload):
+        sha = SHA256.new(payload)
+        if sign_rsa_pss:
+            signer = PKCS1_PSS.new(self.key)
+        else:
+            signer = PKCS1_v1_5.new(self.key)
+        signature = signer.sign(sha)
+        assert len(signature) == self.sig_len()
+        return signature
+
+class ECDSA256P1():
+    def __init__(self, key):
+        """Construct an ECDSA P-256 private key"""
+        self.key = key
+
+    @staticmethod
+    def generate():
+        return ECDSA256P1(SigningKey.generate(curve=NIST256p))
+
+    def export_private(self, path):
+        with open(path, 'wb') as f:
+            f.write(self.key.to_pem())
+
+    def get_public_bytes(self):
+        vk = self.key.get_verifying_key()
+        return bytes(vk.to_der())
+
+    def emit_c(self):
+        vk = self.key.get_verifying_key()
+        print(AUTOGEN_MESSAGE)
+        print("const unsigned char ecdsa_pub_key[] = {", end='')
+        encoded = bytes(vk.to_der())
+        for count, b in enumerate(encoded):
+            if count % 8 == 0:
+                print("\n\t", end='')
+            else:
+                print(" ", end='')
+            print("0x{:02x},".format(b), end='')
+        print("\n};")
+        print("const unsigned int ecdsa_pub_key_len = {};".format(len(encoded)))
+
+    def emit_rust(self):
+        vk = self.key.get_verifying_key()
+        print(AUTOGEN_MESSAGE)
+        print("static ECDSA_PUB_KEY: &'static [u8] = &[", end='')
+        encoded = bytes(vk.to_der())
+        for count, b in enumerate(encoded):
+            if count % 8 == 0:
+                print("\n    ", end='')
+            else:
+                print(" ", end='')
+            print("0x{:02x},".format(b), end='')
+        print("\n];")
+
+    def sign(self, payload):
+        # To make this fixed length, possibly pad with zeros.
+        sig = self.key.sign(payload, hashfunc=hashlib.sha256, sigencode=util.sigencode_der)
+        sig += b'\000' * (self.sig_len() - len(sig))
+        return sig
+
+    def sig_len(self):
+        # The DER encoding depends on the high bit, and can be
+        # anywhere from 70 to 72 bytes.  Because we have to fill in
+        # the length field before computing the signature, however,
+        # we'll give the largest, and the sig checking code will allow
+        # for it to be up to two bytes larger than the actual
+        # signature.
+        return 72
+
+    def sig_type(self):
+        """Return the type of this signature (as a string)"""
+        return "ECDSA256_SHA256"
+
+    def sig_tlv(self):
+        return "ECDSA256"
+
+def load(path):
+    with open(path, 'rb') as f:
+        pem = f.read()
+    try:
+        key = RSA.importKey(pem)
+        if key.n.bit_length() != 2048:
+            raise Exception("Unsupported RSA bit length, only 2048 supported")
+        return RSA2048(key)
+    except ValueError:
+        key = SigningKey.from_pem(pem)
+        if key.curve.name != 'NIST256p':
+            raise Exception("Unsupported ECDSA curve")
+        return ECDSA256P1(key)