Files @ b52e197db5a8
Branch filter:

Location: Shamira/src/cli.py

Laman
better exception handling
# GNU GPLv3, see LICENSE

from argparse import ArgumentParser

from shamira import generate, reconstruct, SException


def run():
	parser=ArgumentParser()
	subparsers=parser.add_subparsers()

	buildSplitParser(subparsers.add_parser("split"))
	buildJoinParser(subparsers.add_parser("join"))

	parser.set_defaults(func=lambda _: parser.error("missing command"))

	args=parser.parse_args()
	args.func(args)


def buildSplitParser(parser):
	parser.add_argument("-k",type=int,required=True,help="number of shares necessary for recovering the secret")
	parser.add_argument("-n",type=int,required=True,help="number of generated shares")

	encoding=parser.add_mutually_exclusive_group()
	encoding.add_argument("--hex",action="store_true",help="encode shares' bytes as a hexadecimal string")
	encoding.add_argument("--b32",action="store_true",help="encode shares' bytes as a base32 string")
	encoding.add_argument("--b64",action="store_true",help="encode shares' bytes as a base64 string")

	parser.add_argument("secret",help="secret to be parsed")
	parser.set_defaults(func=_generate)
	

def buildJoinParser(parser):
	encoding=parser.add_mutually_exclusive_group()
	encoding.add_argument("--hex",action="store_true",help="decode shares' bytes from a hexadecimal string")
	encoding.add_argument("--b32",action="store_true",help="decode shares' bytes from a base32 string")
	encoding.add_argument("--b64",action="store_true",help="decode shares' bytes from a base64 string")

	parser.add_argument("-r","--raw",action="store_true",help="return secret as raw bytes")
	parser.add_argument("share",nargs="+",help="shares to be joined")
	parser.set_defaults(func=_reconstruct)


def _generate(args):
	encoding=getEncoding(args) or "b32"

	try:
		shares=generate(args.secret,args.k,args.n,encoding)
		for s in shares:
			print(s)
	except SException as e:
		print(e)


def _reconstruct(args):
	encoding=getEncoding(args)
	try:
		print(reconstruct(*args.share,encoding=encoding,raw=args.raw))
	except SException as e:
		print(e)


def getEncoding(args):
	if args.hex: return "hex"
	elif args.b32: return "b32"
	elif args.b64: return "b64"
	else: return ""