|
1 | 1 | from __future__ import division
|
2 | 2 |
|
| 3 | +from six import PY2 |
3 | 4 | from . import der, ecdsa, ellipticcurve
|
4 | 5 | from .util import orderlen, number_to_string, string_to_number
|
5 | 6 | from ._compat import normalise_bytes
|
@@ -79,6 +80,9 @@ def to_der(self, encoding=None, point_encoding="uncompressed"):
|
79 | 80 | :param str point_encoding: the point encoding of the generator when
|
80 | 81 | explicit curve encoding is used. Ignored for ``named_curve``
|
81 | 82 | format.
|
| 83 | +
|
| 84 | + :return: DER encoded ECParameters structure |
| 85 | + :rtype: bytes |
82 | 86 | """
|
83 | 87 | if encoding is None:
|
84 | 88 | if self.oid:
|
@@ -117,6 +121,24 @@ def to_der(self, encoding=None, point_encoding="uncompressed"):
|
117 | 121 |
|
118 | 122 | return der.encode_sequence(*seq_elements)
|
119 | 123 |
|
| 124 | + def to_pem(self, encoding=None, point_encoding="uncompressed"): |
| 125 | + """ |
| 126 | + Serialise the curve parameters to the :term:`PEM` format. |
| 127 | +
|
| 128 | + :param str encoding: the format to save the curve parameters in. |
| 129 | + Default is ``named_curve``, with fallback being the ``explicit`` |
| 130 | + if the OID is not set for the curve. |
| 131 | + :param str point_encoding: the point encoding of the generator when |
| 132 | + explicit curve encoding is used. Ignored for ``named_curve`` |
| 133 | + format. |
| 134 | +
|
| 135 | + :return: PEM encoded ECParameters structure |
| 136 | + :rtype: str |
| 137 | + """ |
| 138 | + return der.topem( |
| 139 | + self.to_der(encoding, point_encoding), "EC PARAMETERS" |
| 140 | + ) |
| 141 | + |
120 | 142 | @staticmethod
|
121 | 143 | def from_der(data):
|
122 | 144 | """Decode the curve parameters from DER file.
|
@@ -190,6 +212,21 @@ def from_der(data):
|
190 | 212 | return i
|
191 | 213 | return tmp_curve
|
192 | 214 |
|
| 215 | + @classmethod |
| 216 | + def from_pem(cls, string): |
| 217 | + """Decode the curve parameters from PEM file. |
| 218 | +
|
| 219 | + :param str string: the text string to decode the parameters from |
| 220 | + """ |
| 221 | + if not PY2 and isinstance(string, str): # pragma: no branch |
| 222 | + string = string.encode() |
| 223 | + |
| 224 | + ec_param_index = string.find(b"-----BEGIN EC PARAMETERS-----") |
| 225 | + if ec_param_index == -1: |
| 226 | + raise der.UnexpectedDER("EC PARAMETERS PEM header not found") |
| 227 | + |
| 228 | + return cls.from_der(der.unpem(string[ec_param_index:])) |
| 229 | + |
193 | 230 |
|
194 | 231 | # the SEC curves
|
195 | 232 | SECP112r1 = Curve(
|
|
0 commit comments