pem_to_pub_c.py: Rework code to be more pythonic
Instances of open() were wrapped in with statements to ensure proper
closing of files even in the case of errors. This also improves
the readability of the code.
Signed-off-by: Markus S. Wamser <markus.wamser@mixed-mode.de>
Reviewed-by: Etienne Carriere <etienne.carriere@linaro.org>
Reviewed-by: Joakim Bech <joakim.bech@linaro.org>
[jf: add file name to commit subject and use imperative mood]
Signed-off-by: Jerome Forissier <jerome.forissier@linaro.org>
diff --git a/scripts/pem_to_pub_c.py b/scripts/pem_to_pub_c.py
index a1a9bc9..8cd1044 100755
--- a/scripts/pem_to_pub_c.py
+++ b/scripts/pem_to_pub_c.py
@@ -2,7 +2,6 @@
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2015, Linaro Limited
-#
def get_args():
@@ -10,13 +9,11 @@
parser = argparse.ArgumentParser()
parser.add_argument(
- '--prefix',
- required=True,
+ '--prefix', required=True,
help='Prefix for the public key exponent and modulus in c file')
-
- parser.add_argument('--out', required=True,
- help='Name of c file for the public key')
-
+ parser.add_argument(
+ '--out', required=True,
+ help='Name of c file for the public key')
parser.add_argument('--key', required=True, help='Name of key file')
return parser.parse_args()
@@ -29,9 +26,8 @@
args = get_args()
- f = open(args.key, 'r')
- key = RSA.importKey(f.read())
- f.close
+ with open(args.key, 'r') as f:
+ key = RSA.importKey(f.read())
# Refuse public exponent with more than 32 bits. Otherwise the C
# compiler may simply truncate the value and proceed.
@@ -42,29 +38,23 @@
'Unsupported large public exponent detected. ' +
'OP-TEE handles only public exponents up to 2^32 - 1.')
- f = open(args.out, 'w')
-
- f.write("#include <stdint.h>\n")
- f.write("#include <stddef.h>\n\n")
-
- f.write("const uint32_t " + args.prefix + "_exponent = " +
- str(key.publickey().e) + ";\n\n")
-
- f.write("const uint8_t " + args.prefix + "_modulus[] = {\n")
- i = 0
- for x in array.array("B", long_to_bytes(key.publickey().n)):
- f.write("0x" + '{0:02x}'.format(x) + ",")
- i = i + 1
- if i % 8 == 0:
- f.write("\n")
- else:
- f.write(" ")
- f.write("};\n")
-
- f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" +
- args.prefix + "_modulus);\n")
-
- f.close()
+ with open(args.out, 'w') as f:
+ f.write("#include <stdint.h>\n")
+ f.write("#include <stddef.h>\n\n")
+ f.write("const uint32_t " + args.prefix + "_exponent = " +
+ str(key.publickey().e) + ";\n\n")
+ f.write("const uint8_t " + args.prefix + "_modulus[] = {\n")
+ i = 0
+ for x in array.array("B", long_to_bytes(key.publickey().n)):
+ f.write("0x" + '{0:02x}'.format(x) + ",")
+ i = i + 1
+ if i % 8 == 0:
+ f.write("\n")
+ else:
+ f.write(" ")
+ f.write("};\n")
+ f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" +
+ args.prefix + "_modulus);\n")
if __name__ == "__main__":