scripts/sign.py: support PyCryptodome

Depending on the Linux distribution, the Crypto package may be
provided by PyCrypto [1] or PyCryptodome [2]. For example, Ubuntu has
the former, while Arch Linux comes with the latter.

PyCryptodome is a fork of PyCrypto, which is not maintained any more
(the last release dates back to 2013 [3]). It exposes almost the same
API, but there are a few incompatibilities [4].

Newer versions of PyCryptodome throw NotImplementedError when calling
size() method if RSA object. This is because this method is
considered not safe. But this is only one way to get key size in
PyCrypto.

We will use size_in_bytes() in case if size() is not available.

Also, added sanity check to ensure that computed signature size
equals to actual one.

[1] https://pypi.org/project/pycrypto/
[2] https://pycryptodome.readthedocs.io/en/latest/
[3] https://pypi.org/project/pycrypto/#history
[4] https://pycryptodome.readthedocs.io/en/latest/src/vs_pycrypto.html

Signed-off-by: Volodymyr Babchuk <volodymyr_babchuk@epam.com>
Reviewed-by: Jerome Forissier <jerome.forissier@linaro.org>
Acked-by: Etienne Carriere <etienne.carriere@linaro.org>
Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org>
diff --git a/scripts/sign.py b/scripts/sign.py
index 632a4ef..57df657 100755
--- a/scripts/sign.py
+++ b/scripts/sign.py
@@ -144,7 +144,13 @@
     h = SHA256.new()
 
     digest_len = h.digest_size
-    sig_len = ceil_div(key.size() + 1, 8)
+    try:
+        # This works in pycrypto
+        sig_len = ceil_div(key.size() + 1, 8)
+    except NotImplementedError:
+        # ... and this one - in pycryptodome
+        sig_len = key.size_in_bytes()
+
     img_size = len(img)
 
     hdr_version = args.ta_version  # struct shdr_bootstrap_ta::ta_version
@@ -181,6 +187,10 @@
         else:
             signer = PKCS1_v1_5.new(key)
             sig = signer.sign(h)
+            if len(sig) != sig_len:
+                raise Exception(("Actual signature length is not equal to ",
+                                 "the computed one: {} != {}").
+                                format(len(sig), sig_len))
             write_image_with_signature(sig)
             logger.info('Successfully signed application.')