Changeset - b52e197db5a8
[Not reviewed]
default
0 5 0
Laman - 7 years ago 2017-10-01 18:45:34

better exception handling
5 files changed with 38 insertions and 23 deletions:
0 comments (0 inline, 0 general)
src/cli.py
Show inline comments
 
# GNU GPLv3, see LICENSE
 

	
 
from argparse import ArgumentParser
 

	
 
from shamira import generate, reconstruct
 
from shamira import generate, reconstruct, SException
 

	
 

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

	
 
@@ -46,22 +46,22 @@ 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 ValueError as e:
 
		print("operation failed: ",e)
 
	except SException as e:
 
		print(e)
 

	
 

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

	
 

	
 
def getEncoding(args):
 
	if args.hex: return "hex"
 
	elif args.b32: return "b32"
 
	elif args.b64: return "b64"
src/condensed.py
Show inline comments
 
@@ -49,12 +49,15 @@ def getConstantCoef(*points):
 
###
 

	
 
import base64
 
import binascii
 

	
 

	
 
class SException(Exception): pass
 

	
 

	
 
def reconstructRaw(*shares):
 
	"""Tries to recover the secret from its shares.
 

	
 
	:param shares: ((i, (bytes) share), ...)
 
	:return: (bytes) reconstructed secret. Too few shares returns garbage."""
 
	secretLen=len(shares[0][1])
 
@@ -69,27 +72,29 @@ def reconstruct(*shares):
 
	"""Wraps reconstructRaw.
 

	
 
	:param shares: ((str) share, ...)
 
	:return: (str) reconstructed secret. Too few shares returns garbage."""
 

	
 
	bs=reconstructRaw(*(decode(s) for s in shares))
 
	return bs.decode(encoding="utf-8")
 

	
 
	try:
 
		return bs.decode(encoding="utf-8")
 
	except UnicodeDecodeError:
 
		raise SException('Failed to decode bytes to utf-8. Either you supplied invalid shares, or you missed the "raw" flag. Offending value: "{0}"'.format(bs))
 

	
 

	
 
def decode(share):
 
	try:
 
		(i,_,shareStr)=share.partition(".")
 
		i=int(i)
 
		if not 1<=i<=255:
 
			raise ValueError()
 
			raise SException("Malformed share: Failed 1<=k<=255, k={0}".format(i))
 

	
 
		shareBytes=base64.b32decode(shareStr)
 
		return (i,shareBytes)
 
	except (ValueError,binascii.Error):
 
		raise ValueError('bad share format: share="{0}"'.format(share))
 
		raise SException('Malformed share: share="{0}"'.format(share))
 

	
 
###
 

	
 
from argparse import ArgumentParser
 

	
 

	
 
@@ -106,11 +111,11 @@ def run():
 
	args=parser.parse_args()
 
	args.func(args)
 

	
 

	
 
def _reconstruct(args):
 
	try: print(reconstruct(*args.share))
 
	except ValueError as e: print("operation failed: ",e)
 
	except SException as e: print(e)
 

	
 

	
 
if __name__=="__main__":
 
	run()
src/shamira.py
Show inline comments
 
@@ -5,15 +5,22 @@ import re
 
import base64
 
import binascii
 

	
 
import gf256
 

	
 

	
 
class SException(Exception): pass
 
class InvalidParams(SException): pass
 
class DetectionException(SException): pass
 
class DecodingException(SException): pass
 
class MalformedShare(SException): pass
 

	
 

	
 
def _shareByte(secretB,k,n):
 
	if not k<=n<255:
 
		raise ValueError("failing k<=n<255, k={0}, n={1}".format(k,n))
 
		raise InvalidParams("Failed k<=n<255, k={0}, n={1}".format(k,n))
 
	coefs=[int(secretB)]+[int(b) for b in os.urandom(k-1)]
 
	points=[gf256.evaluate(coefs,i) for i in range(1,n+1)]
 
	return points
 

	
 

	
 
def generateRaw(secret,k,n):
 
@@ -62,13 +69,16 @@ def reconstruct(*shares,encoding="",raw=
 
	:param raw: (bool) whether to return bytes (True) or str (False)
 
	:return: (str or bytes) reconstructed secret. Too few shares returns garbage."""
 
	if not encoding:
 
		encoding=detectEncoding(shares)
 

	
 
	bs=reconstructRaw(*(decode(s,encoding) for s in shares))
 
	return bs if raw else bs.decode(encoding="utf-8")
 
	try:
 
		return bs if raw else bs.decode(encoding="utf-8")
 
	except UnicodeDecodeError:
 
		raise DecodingException('Failed to decode bytes to utf-8. Either you supplied invalid shares, or you missed the "raw" flag. Offending value: {0}'.format(bs))
 

	
 

	
 
def encode(share,encoding="b32"):
 
	if encoding=="hex": f=base64.b16encode
 
	elif encoding=="b32": f=base64.b32encode
 
	else: f=base64.b64encode
 
@@ -78,31 +88,31 @@ def encode(share,encoding="b32"):
 

	
 
def decode(share,encoding="b32"):
 
	try:
 
		(i,_,shareStr)=share.partition(".")
 
		i=int(i)
 
		if not 1<=i<=255:
 
			raise ValueError()
 
			raise MalformedShare("Malformed share: Failed 1<=k<=255, k={0}".format(i))
 
		if encoding=="hex": f=base64.b16decode
 
		elif encoding=="b32": f=base64.b32decode
 
		else: f=base64.b64decode
 
		shareBytes=f(shareStr)
 
		return (i,shareBytes)
 
	except (ValueError,binascii.Error):
 
		raise ValueError('bad share format: share="{0}", encoding="{1}"'.format(share,encoding))
 
		raise MalformedShare('Malformed share: share="{0}", encoding="{1}"'.format(share,encoding))
 

	
 

	
 
def detectEncoding(shares):
 
	classes=[
 
		(re.compile(r"\d+\.([0-9A-F]{2})+"), "hex"),
 
		(re.compile(r"\d+\.([A-Z2-7]{8})*([A-Z2-7]{8}|[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}={1})"), "b32"),
 
		(re.compile(r"\d+\.([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{2}={2}|[A-Za-z0-9+/]{3}={1})"), "b64")
 
	]
 
	for (regexp, res) in classes:
 
		if all(regexp.fullmatch(share) for share in shares):
 
			return res
 
	raise ValueError("no expected encoding detected")
 
	raise DetectionException("No expected encoding detected")
 

	
 

	
 
if __name__=="__main__":
 
	import cli
 
	cli.run()
src/tests/test_condensed.py
Show inline comments
 
@@ -67,20 +67,20 @@ class TestCondensed(TestCase):
 
				with self.subTest(sec=secret,k=k,n=n):
 
					shares=generate(secret,k,n)
 
					random.shuffle(shares)
 
					self.assertEqual(reconstruct(*shares[:k]), secret)
 
					try:
 
						self.assertNotEqual(reconstruct(*shares[:k-1]), secret)
 
					except UnicodeDecodeError:
 
					except SException:
 
						pass
 
		shares=generate(b"\xfeaa",2,3)
 
		with self.assertRaises(UnicodeDecodeError):
 
		with self.assertRaises(SException):
 
			reconstruct(*shares)
 

	
 
	def testDecode(self):
 
		with self.assertRaises(ValueError):
 
		with self.assertRaises(SException):
 
			decode("AAA")
 
			decode("1.")
 
			decode(".AAA")
 
			decode("1AAA")
 
			decode("1.AAAQEAY")
 
			decode("1.AAAQEAy=")
src/tests/test_shamira.py
Show inline comments
 
@@ -17,15 +17,15 @@ class TestShamira(TestCase):
 

	
 
	@classmethod
 
	def tearDownClass(cls):
 
		os.urandom=cls._urandom
 

	
 
	def test_shareByte(self):
 
		with self.assertRaises(ValueError): # too few shares
 
		with self.assertRaises(InvalidParams): # too few shares
 
			_shareByte(b"a",5,4)
 
		with self.assertRaises(ValueError): # too many shares
 
		with self.assertRaises(InvalidParams): # too many shares
 
			_shareByte(b"a",5,255)
 
		with self.assertRaises(ValueError): # not castable to int
 
			_shareByte("x",2,3)
 

	
 
		vals=_shareByte(ord(b"a"),2,3)
 
		points=list(zip(range(1,256), vals))
 
@@ -50,23 +50,23 @@ class TestShamira(TestCase):
 
						random.shuffle(shares)
 
						self.assertEqual(reconstruct(*shares[:k],encoding=encoding,raw=raw), secret)
 
						self.assertEqual(reconstruct(*shares[:k],raw=raw), secret)
 
						s=secret if raw else secret.encode("utf-8")
 
						self.assertNotEqual(reconstruct(*shares[:k-1],encoding=encoding,raw=True), s)
 
		shares=generate(b"\xfeaa",2,3)
 
		with self.assertRaises(UnicodeDecodeError):
 
		with self.assertRaises(DecodingException):
 
			reconstruct(*shares)
 

	
 
	def testEncode(self):
 
		share=(2,b"\x00\x01\x02")
 
		for (encoding,encodedStr) in [("hex",'000102'),("b32",'AAAQE==='),("b64",'AAEC')]:
 
			with self.subTest(enc=encoding):
 
				self.assertEqual(encode(share,encoding), "2."+encodedStr)
 

	
 
	def testDecode(self):
 
		with self.assertRaises(ValueError):
 
		with self.assertRaises(MalformedShare):
 
			decode("AAA")
 
			decode("1.")
 
			decode(".AAA")
 
			decode("1AAA")
 
			decode("1.0001020f","hex")
 
			decode("1.000102030","hex")
 
@@ -92,12 +92,12 @@ class TestShamira(TestCase):
 
			["1.000102","2.AAECAw=="],
 
			["1.AAECAw==","2.AAAQE==="],
 
			[".00010203"], # no index
 
			["00010203"] # no index
 
		]:
 
			with self.subTest(shares=shares):
 
				with self.assertRaises(ValueError):
 
				with self.assertRaises(DetectionException):
 
					detectEncoding(shares)
 
		self.assertEqual(detectEncoding(["10.00010203"]), "hex")
 
		self.assertEqual(detectEncoding(["2.AAAQEAY="]), "b32")
 
		self.assertEqual(detectEncoding(["3.AAECAw=="]), "b64")
 
		self.assertEqual(detectEncoding(["3.AAECAwQF","1.00010203"]), "b64")
0 comments (0 inline, 0 general)