diff options
author | Paul Kehrer <paul.l.kehrer@gmail.com> | 2015-10-25 15:44:29 -0500 |
---|---|---|
committer | Paul Kehrer <paul.l.kehrer@gmail.com> | 2015-10-26 08:27:22 -0500 |
commit | 467072f7d50778f064f192b4e318c19c6cf98293 (patch) | |
tree | 9ef70c8cf76f86795f05fc00d22b9db785b9e659 /src/cryptography | |
parent | 9bbf778b7dde2fab6d957f3b5b4422d5bb3ce5a0 (diff) | |
download | cryptography-467072f7d50778f064f192b4e318c19c6cf98293.tar.gz cryptography-467072f7d50778f064f192b4e318c19c6cf98293.tar.bz2 cryptography-467072f7d50778f064f192b4e318c19c6cf98293.zip |
add support for encoding/decoding elliptic curve points
Based on the work of @ronf in #2346.
Diffstat (limited to 'src/cryptography')
-rw-r--r-- | src/cryptography/hazmat/primitives/asymmetric/utils.py | 34 | ||||
-rw-r--r-- | src/cryptography/utils.py | 7 |
2 files changed, 39 insertions, 2 deletions
diff --git a/src/cryptography/hazmat/primitives/asymmetric/utils.py b/src/cryptography/hazmat/primitives/asymmetric/utils.py index bad9ab73..b62eadf0 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/utils.py +++ b/src/cryptography/hazmat/primitives/asymmetric/utils.py @@ -13,6 +13,7 @@ from pyasn1.type import namedtype, univ import six from cryptography import utils +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve class _DSSSigValue(univ.Sequence): @@ -71,3 +72,36 @@ def encode_dss_signature(r, s): sig.setComponentByName('r', r) sig.setComponentByName('s', s) return encoder.encode(sig) + + +def encode_ec_point(curve, x, y): + if not isinstance(curve, EllipticCurve): + raise TypeError("curve must be an EllipticCurve instance") + + if x is None: + return b'\x00' + else: + # Get the ceiling of curve.key_size / 8 + byte_length = (curve.key_size + 7) // 8 + return ( + b'\x04' + utils.int_to_bytes(x, byte_length) + + utils.int_to_bytes(y, byte_length) + ) + + +def decode_ec_point(curve, data): + if not isinstance(curve, EllipticCurve): + raise TypeError("curve must be an EllipticCurve instance") + + if data == b'\x00': + return None, None + elif data.startswith(b'\x04'): + # Get the ceiling of curve.key_size / 8 + byte_length = (curve.key_size + 7) // 8 + if len(data) == 2 * byte_length + 1: + return (utils.int_from_bytes(data[1:byte_length + 1], 'big'), + utils.int_from_bytes(data[byte_length + 1:], 'big')) + else: + raise ValueError('Invalid elliptic curve point data length') + else: + raise ValueError('Unsupported elliptic curve point type') 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))) |