summaryrefslogtreecommitdiff
path: root/scripts/pem_to_pub_c.py
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/pem_to_pub_c.py')
-rwxr-xr-xscripts/pem_to_pub_c.py41
1 files changed, 34 insertions, 7 deletions
diff --git a/scripts/pem_to_pub_c.py b/scripts/pem_to_pub_c.py
index 47c004d..92f4b81 100755
--- a/scripts/pem_to_pub_c.py
+++ b/scripts/pem_to_pub_c.py
@@ -26,6 +26,33 @@
# POSSIBILITY OF SUCH DAMAGE.
#
+from collections import namedtuple
+PublicKey = namedtuple("PublicKey", "e n")
+
+def importKey_crypto(pem_key_file):
+ try:
+ module = __import__("Crypto.PublicKey.RSA")
+ f = open(pem_key_file, 'r')
+ key = module.PublicKey.RSA.importKey(f.read())
+ f.close()
+ return PublicKey(e=key.publickey().e, n=module.Util.number.long_to_bytes(key.publickey().n))
+ except ImportError:
+ return None
+
+def importKey_openssl(pem_key_file):
+ import subprocess
+ cmd = "cat " + pem_key_file + " | openssl rsa -inform PEM -noout -text | grep publicE | sed 's/publicExponent: //' | cut -d ' ' -f1 | tr -d '\n'"
+ e = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
+ if not e:
+ print "Exporting exponent value from key {0} has failed.".format(pem_key_file)
+ return None
+ cmd = "cat " + pem_key_file + " | openssl rsa -inform PEM -noout -modulus | sed 's/Modulus=//' | tr -d '\n'"
+ n = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
+ if not n:
+ print "Exporting modulus value from key {0} has failed.".format(pem_key_file)
+ return None
+ return PublicKey(e=e, n=n.decode("hex"))
+
def get_args():
import argparse
@@ -42,14 +69,14 @@ def get_args():
def main():
import array
- from Crypto.PublicKey import RSA
- from Crypto.Util.number import long_to_bytes
args = get_args();
- f = open(args.key, 'r')
- key = RSA.importKey(f.read())
- f.close
+ key = importKey_crypto(args.key)
+ if key is None:
+ key = importKey_openssl(args.key)
+ if key is None:
+ return
f = open(args.out, 'w')
@@ -57,11 +84,11 @@ def main():
f.write("#include <stddef.h>\n\n");
f.write("const uint32_t " + args.prefix + "_exponent = " +
- str(key.publickey().e) + ";\n\n")
+ str(key.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)):
+ for x in array.array("B", key.n):
f.write("0x" + '{0:02x}'.format(x) + ",")
i = i + 1;
if i % 8 == 0: