imgtool: fix getpriv format type for keys

A previous change was added to allow the `getpriv` command to dump ec256
keys in both openssl and pkcs8. That PR did not touch other key file
types which resulted in errors using that command with RSA, X25519, etc.

This commit generalizes the passing of the `format` parameter, so each
key type can decide which format it allows a dump to be produced in,
and what default to use.

Fixes #1529

Signed-off-by: Fabio Utzig <utzig@apache.org>
diff --git a/scripts/imgtool/keys/privatebytes.py b/scripts/imgtool/keys/privatebytes.py
new file mode 100644
index 0000000..8027ac8
--- /dev/null
+++ b/scripts/imgtool/keys/privatebytes.py
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: Apache-2.0
+
+from cryptography.hazmat.primitives import serialization
+
+
+class PrivateBytesMixin():
+    def _get_private_bytes(self, minimal, format, exclass):
+        if format is None:
+            format = self._DEFAULT_FORMAT
+        if format not in self._VALID_FORMATS:
+            raise exclass("{} does not support {}".format(
+                self.shortname(), format))
+        return format, self.key.private_bytes(
+                encoding=serialization.Encoding.DER,
+                format=self._VALID_FORMATS[format],
+                encryption_algorithm=serialization.NoEncryption())