Package tlslite :: Package utils :: Module ecc
[hide private]
[frames] | no frames]

Source Code for Module tlslite.utils.ecc

 1  # Copyright (c) 2015, Hubert Kario 
 2  # 
 3  # See the LICENSE file for legal information regarding use of this file. 
 4  """Methods for dealing with ECC points""" 
 5   
 6  from .codec import Parser, Writer 
 7  from .cryptomath import bytesToNumber, numberToByteArray, numBytes 
 8  from .compat import ecdsaAllCurves 
 9  import ecdsa 
10   
11 -def decodeX962Point(data, curve=ecdsa.NIST256p):
12 """Decode a point from a X9.62 encoding""" 13 parser = Parser(data) 14 encFormat = parser.get(1) 15 assert encFormat == 4 16 bytelength = getPointByteSize(curve) 17 xCoord = bytesToNumber(parser.getFixBytes(bytelength)) 18 yCoord = bytesToNumber(parser.getFixBytes(bytelength)) 19 return ecdsa.ellipticcurve.Point(curve.curve, xCoord, yCoord)
20
21 -def encodeX962Point(point):
22 """Encode a point in X9.62 format""" 23 bytelength = numBytes(point.curve().p()) 24 writer = Writer() 25 writer.add(4, 1) 26 writer.bytes += numberToByteArray(point.x(), bytelength) 27 writer.bytes += numberToByteArray(point.y(), bytelength) 28 return writer.bytes
29
30 -def getCurveByName(curveName):
31 """Return curve identified by curveName""" 32 curveMap = {'secp256r1':ecdsa.NIST256p, 33 'secp384r1':ecdsa.NIST384p, 34 'secp521r1':ecdsa.NIST521p, 35 'secp256k1':ecdsa.SECP256k1} 36 if ecdsaAllCurves: 37 curveMap['secp224r1'] = ecdsa.NIST224p 38 curveMap['secp192r1'] = ecdsa.NIST192p 39 40 if curveName in curveMap: 41 return curveMap[curveName] 42 else: 43 raise ValueError("Curve of name '{0}' unknown".format(curveName))
44
45 -def getPointByteSize(point):
46 """Convert the point or curve bit size to bytes""" 47 curveMap = {ecdsa.NIST256p.curve: 256//8, 48 ecdsa.NIST384p.curve: 384//8, 49 ecdsa.NIST521p.curve: (521+7)//8, 50 ecdsa.SECP256k1.curve: 256//8} 51 if ecdsaAllCurves: 52 curveMap[ecdsa.NIST224p.curve] = 224//8 53 curveMap[ecdsa.NIST192p.curve] = 192//8 54 55 if hasattr(point, 'curve'): 56 if callable(point.curve): 57 return curveMap[point.curve()] 58 else: 59 return curveMap[point.curve] 60 raise ValueError("Parameter must be a curve or point on curve")
61