From db0e679176c6b54b300bf750dea40a616c0b1d88 Mon Sep 17 00:00:00 2001 From: Lukas Kozak Date: Thu, 20 Jun 2019 02:57:50 +0200 Subject: [PATCH] Improve BLS Bin2Hex tool Added sanity check and automatic detection Signed-off-by: Lukas Kozak --- scripts/bls_bintohex.py | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/scripts/bls_bintohex.py b/scripts/bls_bintohex.py index 76f8ca885..8b9a47a68 100755 --- a/scripts/bls_bintohex.py +++ b/scripts/bls_bintohex.py @@ -1,31 +1,50 @@ #!/usr/bin/env python3 -import argparse -import binascii -import sys +import argparse, binascii +import sys, glob, re, os parser = argparse.ArgumentParser(description='Tool to convert your BLS key from binary to the accepted hex format.') -parser.add_argument('file') -parser.add_argument('-o', '--output', type=str, metavar='output', help='name your keyfile') +parser.add_argument('-i', '--input', type=str, metavar='input', help='path to BLS keyfile') args = parser.parse_args() +## Finds first bls keyfile in the directory or takes file given by user +if args.input: + inputName = args.input + print(inputName) +else: + keylist = glob.glob('UTC*bls_*') + inputName = keylist[0] + +## Read try: - with open(args.file, 'rb') as inputFile: + with open(inputName, 'rb') as inputFile: binFormat = inputFile.read() except IOError: print('File couldn\'t be opened.') sys.exit(1) -hexFormat = binascii.hexlify(binFormat) +## Sanity check and conversion +try: + binascii.unhexlify(binFormat) +except binascii.Error: + hexFormat = binascii.hexlify(binFormat) +else: + print("Keyfile is already in text format, no conversion required!") + sys.exit(0) + +## Name output appropriately based on the public key +matchObj = re.search('UTC.*bls_(.*)', inputName) -if args.output is not None: - outputName = args.output +if matchObj: + outputName = matchObj.group(1) + ".key" else: - outputName = 'PUB.key' + outputName = 'bls.key' +## Write try: - with open(outputName, 'wt') as outputFile: + with open(outputName, 'w') as outputFile: outputFile.write(hexFormat.decode('ascii')) + print("Keyfile converted to: {}".format(outputName)) except IOError: print('File couldn\'t be written.') sys.exit(1)