aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorAlex Gaynor <alex.gaynor@gmail.com>2015-10-27 22:17:13 -0400
committerAlex Gaynor <alex.gaynor@gmail.com>2015-10-27 22:17:13 -0400
commitd3f4ecdbefe20f4f9cb8b74701c5757557e476e1 (patch)
tree7bd4e100c3536859936c6453208f956719f1d7c5 /src
parentcab8db3e9535a3900602931cb84d3f273f685d47 (diff)
parent197db3367ceecdbaf0adc5eaa9339b934b10acfe (diff)
downloadcryptography-d3f4ecdbefe20f4f9cb8b74701c5757557e476e1.tar.gz
cryptography-d3f4ecdbefe20f4f9cb8b74701c5757557e476e1.tar.bz2
cryptography-d3f4ecdbefe20f4f9cb8b74701c5757557e476e1.zip
Merge pull request #2447 from reaperhulk/encode-decode-point
add support for encoding/decoding elliptic curve points
Diffstat (limited to 'src')
-rw-r--r--src/cryptography/hazmat/primitives/asymmetric/ec.py25
-rw-r--r--src/cryptography/utils.py7
2 files changed, 30 insertions, 2 deletions
diff --git a/src/cryptography/hazmat/primitives/asymmetric/ec.py b/src/cryptography/hazmat/primitives/asymmetric/ec.py
index c6f83667..7782133c 100644
--- a/src/cryptography/hazmat/primitives/asymmetric/ec.py
+++ b/src/cryptography/hazmat/primitives/asymmetric/ec.py
@@ -259,6 +259,31 @@ class EllipticCurvePublicNumbers(object):
def public_key(self, backend):
return backend.load_elliptic_curve_public_numbers(self)
+ def encode_point(self):
+ # key_size is in bits. Convert to bytes and round up
+ byte_length = (self.curve.key_size + 7) // 8
+ return (
+ b'\x04' + utils.int_to_bytes(self.x, byte_length) +
+ utils.int_to_bytes(self.y, byte_length)
+ )
+
+ @classmethod
+ def from_encoded_point(cls, curve, data):
+ if not isinstance(curve, EllipticCurve):
+ raise TypeError("curve must be an EllipticCurve instance")
+
+ if data.startswith(b'\x04'):
+ # key_size is in bits. Convert to bytes and round up
+ byte_length = (curve.key_size + 7) // 8
+ if len(data) == 2 * byte_length + 1:
+ x = utils.int_from_bytes(data[1:byte_length + 1], 'big')
+ y = utils.int_from_bytes(data[byte_length + 1:], 'big')
+ return cls(x, y, curve)
+ else:
+ raise ValueError('Invalid elliptic curve point data length')
+ else:
+ raise ValueError('Unsupported elliptic curve point type')
+
curve = utils.read_only_property("_curve")
x = utils.read_only_property("_x")
y = utils.read_only_property("_y")
diff --git a/src/cryptography/utils.py b/src/cryptography/utils.py
index dac4046d..dbd961f7 100644
--- a/src/cryptography/utils.py
+++ b/src/cryptography/utils.py
@@ -48,9 +48,12 @@ else:
return result
-def int_to_bytes(integer):
+def int_to_bytes(integer, length=None):
hex_string = '%x' % integer
- n = len(hex_string)
+ if length is None:
+ n = len(hex_string)
+ else:
+ n = length * 2
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))