from __future__ import absolute_import import Queue, threading class DummyReply: """ A reply object that does nothing. Useful when we need an object to seem like it has a channel, and during testing. """ def __init__(self): self.acked = False def __call__(self, msg=False): self.acked = True class Reply: """ Messages sent through a channel are decorated with a "reply" attribute. This object is used to respond to the message through the return channel. """ def __init__(self, obj): self.obj = obj self.q = Queue.Queue() self.acked = False def __call__(self, msg=None): if not self.acked: self.acked = True if msg is None: self.q.put(self.obj) else: self.q.put(msg) class Channel: def __init__(self, q, should_exit): self.q = q self.should_exit = should_exit def ask(self, mtype, m): """ Decorate a message with a reply attribute, and send it to the master. then wait for a response. """ m.reply = Reply(m) self.q.put((mtype, m)) while not self.should_exit.is_set(): try: # The timeout is here so we can handle a should_exit event. g = m.reply.q.get(timeout=0.5) except Queue.Empty: # pragma: nocover continue return g def tell(self, mtype, m): """ Decorate a message with a dummy reply attribute, send it to the master, then return immediately. """ m.reply = DummyReply() self.q.put((mtype, m)) class Slave(threading.Thread): """ Slaves get a channel end-point through which they can send messages to the master. """ def __init__(self, channel, server): self.channel, self.server = channel, server self.server.set_channel(channel) threading.Thread.__init__(self) self.name = "SlaveThread (%s:%s)" % (self.server.address.host, self.server.address.port) def run(self): self.server.serve_forever() class Master(object): """ Masters get and respond to messages from slaves. """ def __init__(self, server): """ server may be None if no server is needed. """ self.server = server self.masterq = Queue.Queue() self.should_exit = threading.Event() def tick(self, q, timeout): changed = False try: # This endless loop runs until the 'Queue.Empty' # exception is thrown. If more than one request is in # the queue, this speeds up every request by 0.1 seconds, # because get_input(..) function is not blocking. while True: msg = q.get(timeout=timeout) self.handle(*msg) changed = True except Queue.Empty: pass return changed def run(self): self.should_exit.clear() self.server.start_slave(Slave, Channel(self.masterq, self.should_exit)) while not self.should_exit.is_set(): # Don't choose a very small timeout in Python 2: # https://github.com/mitmproxy/mitmproxy/issues/443 # TODO: Lower the timeout value if we move to Python 3. self.tick(self.masterq, 0.1) self.shutdown() def handle(self, mtype, obj): c = "handle_" + mtype m = getattr(self, c, None) if m: m(obj) else: obj.reply() def shutdown(self): if not self.should_exit.is_set(): self.should_exit.set() if self.server: self.server.shutdown() 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import itertools
import os
import pytest
from cryptography import exceptions, utils
from cryptography.hazmat.backends.interfaces import (
EllipticCurveBackend, PEMSerializationBackend
)
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import (
encode_rfc6979_signature
)
from ...utils import (
load_fips_ecdsa_key_pair_vectors, load_fips_ecdsa_signing_vectors,
load_vectors_from_file, raises_unsupported_algorithm
)
_HASH_TYPES = {
"SHA-1": hashes.SHA1,
"SHA-224": hashes.SHA224,
"SHA-256": hashes.SHA256,
"SHA-384": hashes.SHA384,
"SHA-512": hashes.SHA512,
}
def _skip_if_no_serialization(key, backend):
if not isinstance(
key, (
ec.EllipticCurvePrivateKeyWithSerialization,
ec.EllipticCurvePublicKeyWithSerialization
)
):
pytest.skip(
"{0} does not support EC key serialization".format(backend)
)
def _skip_ecdsa_vector(backend, curve_type, hash_type):
if not backend.elliptic_curve_signature_algorithm_supported(
ec.ECDSA(hash_type()),
curve_type()
):
pytest.skip(
"ECDSA not supported with this hash {0} and curve {1}".format(
hash_type().name, curve_type().name
)
)
def _skip_curve_unsupported(backend, curve):
if not backend.elliptic_curve_supported(curve):
pytest.skip(
"Curve {0} is not supported by this backend {1}".format(
curve.name, backend
)
)
@utils.register_interface(ec.EllipticCurve)
class DummyCurve(object):
name = "dummy-curve"
key_size = 1
@utils.register_interface(ec.EllipticCurveSignatureAlgorithm)
class DummySignatureAlgorithm(object):
algorithm = None
@utils.register_interface(serialization.KeySerializationEncryption)
class DummyKeyEncryption(object):
pass
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
def test_skip_curve_unsupported(backend):
with pytest.raises(pytest.skip.Exception):
_skip_curve_unsupported(backend, DummyCurve())
def test_skip_no_serialization():
with pytest.raises(pytest.skip.Exception):
_skip_if_no_serialization("fakebackend", "fakekey")
def test_ec_numbers():
numbers = ec.EllipticCurvePrivateNumbers(
1,
ec.EllipticCurvePublicNumbers(
2, 3, DummyCurve()
)
)
assert numbers.private_value == 1
assert numbers.public_numbers.x == 2
assert numbers.public_numbers.y == 3
assert isinstance(numbers.public_numbers.curve, DummyCurve)
with pytest.raises(TypeError):
ec.EllipticCurvePrivateNumbers(
None,
ec.EllipticCurvePublicNumbers(
2, 3, DummyCurve()
)
)
with pytest.raises(TypeError):
ec.EllipticCurvePrivateNumbers(
1,
ec.EllipticCurvePublicNumbers(
None, 3, DummyCurve()
)
)
with pytest.raises(TypeError):
ec.EllipticCurvePrivateNumbers(
1,
ec.EllipticCurvePublicNumbers(
2, None, DummyCurve()
)
)
with pytest.raises(TypeError):
ec.EllipticCurvePrivateNumbers(
1,
ec.EllipticCurvePublicNumbers(
2, 3, None
)
)
with pytest.raises(TypeError):
ec.EllipticCurvePrivateNumbers(
1,
None
)
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
class TestECWithNumbers(object):
@pytest.mark.parametrize(
("vector", "hash_type"),
list(itertools.product(
load_vectors_from_file(
os.path.join(
"asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"),
load_fips_ecdsa_key_pair_vectors
),
_HASH_TYPES.values()
))
)
def test_with_numbers(self, backend, vector, hash_type):
curve_type = ec._CURVE_TYPES[vector['curve']]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePrivateNumbers(
vector['d'],
ec.EllipticCurvePublicNumbers(
vector['x'],
vector['y'],
curve_type()
)
).private_key(backend)
assert key
if isinstance(key, ec.EllipticCurvePrivateKeyWithSerialization):
priv_num = key.private_numbers()
assert priv_num.private_value == vector['d']
assert priv_num.public_numbers.x == vector['x']
assert priv_num.public_numbers.y == vector['y']
assert curve_type().name == priv_num.public_numbers.curve.name
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
class TestECDSAVectors(object):
@pytest.mark.parametrize(
("vector", "hash_type"),
list(itertools.product(
load_vectors_from_file(
os.path.join(
"asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"),
load_fips_ecdsa_key_pair_vectors
),
_HASH_TYPES.values()
))
)
def test_signing_with_example_keys(self, backend, vector, hash_type):
curve_type = ec._CURVE_TYPES[vector['curve']]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePrivateNumbers(
vector['d'],
ec.EllipticCurvePublicNumbers(
vector['x'],
vector['y'],
curve_type()
)
).private_key(backend)
assert key
pkey = key.public_key()
assert pkey
signer = key.signer(ec.ECDSA(hash_type()))
signer.update(b"YELLOW SUBMARINE")
signature = signer.finalize()
verifier = pkey.verifier(signature, ec.ECDSA(hash_type()))
verifier.update(b"YELLOW SUBMARINE")
verifier.verify()
@pytest.mark.parametrize(
"curve", ec._CURVE_TYPES.values()
)
def test_generate_vector_curves(self, backend, curve):
_skip_curve_unsupported(backend, curve())
key = ec.generate_private_key(curve(), backend)
assert key
assert isinstance(key.curve, curve)
assert key.curve.key_size
pkey = key.public_key()
assert pkey
assert isinstance(pkey.curve, curve)
assert key.curve.key_size == pkey.curve.key_size
def test_generate_unknown_curve(self, backend):
with raises_unsupported_algorithm(
exceptions._Reasons.UNSUPPORTED_ELLIPTIC_CURVE
):
ec.generate_private_key(DummyCurve(), backend)
assert backend.elliptic_curve_signature_algorithm_supported(
ec.ECDSA(hashes.SHA256()),
DummyCurve()
) is False
def test_unknown_signature_algoritm(self, backend):
_skip_curve_unsupported(backend, ec.SECP192R1())
key = ec.generate_private_key(ec.SECP192R1(), backend)
with raises_unsupported_algorithm(
exceptions._Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
):
key.signer(DummySignatureAlgorithm())
with raises_unsupported_algorithm(
exceptions._Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
):
key.public_key().verifier(b"", DummySignatureAlgorithm())
assert backend.elliptic_curve_signature_algorithm_supported(
DummySignatureAlgorithm(),
ec.SECP192R1()
) is False
def test_load_invalid_ec_key_from_numbers(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
numbers = ec.EllipticCurvePrivateNumbers(
357646505660320080863666618182642070958081774038609089496899025506,
ec.EllipticCurvePublicNumbers(
47250808410327023131573602008345894927686381772325561185532964,
1120253292479243545483756778742719537373113335231773536789915,
ec.SECP256R1(),
)
)
with pytest.raises(ValueError):
numbers.private_key(backend)
numbers = ec.EllipticCurvePrivateNumbers(
357646505660320080863666618182642070958081774038609089496899025506,
ec.EllipticCurvePublicNumbers(
-4725080841032702313157360200834589492768638177232556118553296,
1120253292479243545483756778742719537373113335231773536789915,
ec.SECP256R1(),
)
)
with pytest.raises(ValueError):
numbers.private_key(backend)
numbers = ec.EllipticCurvePrivateNumbers(
357646505660320080863666618182642070958081774038609089496899025506,
ec.EllipticCurvePublicNumbers(
47250808410327023131573602008345894927686381772325561185532964,
-1120253292479243545483756778742719537373113335231773536789915,
ec.SECP256R1(),
)
)
with pytest.raises(ValueError):
numbers.private_key(backend)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join(
"asymmetric", "ECDSA", "FIPS_186-3", "SigGen.txt"),
load_fips_ecdsa_signing_vectors
)
)
def test_signatures(self, backend, vector):
hash_type = _HASH_TYPES[vector['digest_algorithm']]
curve_type = ec._CURVE_TYPES[vector['curve']]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePublicNumbers(
vector['x'],
vector['y'],
curve_type()
).public_key(backend)
signature = encode_rfc6979_signature(vector['r'], vector['s'])
verifier = key.verifier(
signature,
ec.ECDSA(hash_type())
)
verifier.update(vector['message'])
assert verifier.verify()
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join(
"asymmetric", "ECDSA", "FIPS_186-3", "SigVer.rsp"),
load_fips_ecdsa_signing_vectors
)
)
def test_signature_failures(self, backend, vector):
hash_type = _HASH_TYPES[vector['digest_algorithm']]
curve_type = ec._CURVE_TYPES[vector['curve']]
_skip_ecdsa_vector(backend, curve_type, hash_type)
key = ec.EllipticCurvePublicNumbers(
vector['x'],
vector['y'],
curve_type()
).public_key(backend)
signature = encode_rfc6979_signature(vector['r'], vector['s'])
verifier = key.verifier(
signature,
ec.ECDSA(hash_type())
)
verifier.update(vector['message'])
if vector["fail"] is True:
with pytest.raises(exceptions.InvalidSignature):
verifier.verify()
else:
verifier.verify()
class TestECNumbersEquality(object):
def test_public_numbers_eq(self):
pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
assert pub == ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
def test_public_numbers_ne(self):
pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
assert pub != ec.EllipticCurvePublicNumbers(1, 2, ec.SECP384R1())
assert pub != ec.EllipticCurvePublicNumbers(1, 3, ec.SECP192R1())
assert pub != ec.EllipticCurvePublicNumbers(2, 2, ec.SECP192R1())
assert pub != object()
def test_private_numbers_eq(self):
pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
priv = ec.EllipticCurvePrivateNumbers(1, pub)
assert priv == ec.EllipticCurvePrivateNumbers(
1, ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
)
def test_private_numbers_ne(self):
pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
priv = ec.EllipticCurvePrivateNumbers(1, pub)
assert priv != ec.EllipticCurvePrivateNumbers(
2, ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
)
assert priv != ec.EllipticCurvePrivateNumbers(
1, ec.EllipticCurvePublicNumbers(2, 2, ec.SECP192R1())
)
assert priv != ec.EllipticCurvePrivateNumbers(
1, ec.EllipticCurvePublicNumbers(1, 3, ec.SECP192R1())
)
assert priv != ec.EllipticCurvePrivateNumbers(
1, ec.EllipticCurvePublicNumbers(1, 2, ec.SECP521R1())
)
assert priv != object()
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
@pytest.mark.requires_backend_interface(interface=PEMSerializationBackend)
class TestECSerialization(object):
@pytest.mark.parametrize(
("fmt", "password"),
itertools.product(
[
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.PrivateFormat.PKCS8
],
[
b"s",
b"longerpassword",
b"!*$&(@#$*&($T@%_somesymbols",
b"\x01" * 1000,
]
)
)
def test_private_bytes_encrypted_pem(self, backend, fmt, password):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: pemfile.read().encode()
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
_skip_if_no_serialization(key, backend)
serialized = key.private_bytes(
serialization.Encoding.PEM,
fmt,
serialization.BestAvailableEncryption(password)
)
loaded_key = serialization.load_pem_private_key(
serialized, password, backend
)
loaded_priv_num = loaded_key.private_numbers()
priv_num = key.private_numbers()
assert loaded_priv_num == priv_num
@pytest.mark.parametrize(
("fmt", "password"),
[
[serialization.PrivateFormat.PKCS8, b"s"],
[serialization.PrivateFormat.PKCS8, b"longerpassword"],
[serialization.PrivateFormat.PKCS8, b"!*$&(@#$*&($T@%_somesymbol"],
[serialization.PrivateFormat.PKCS8, b"\x01" * 1000]
]
)
def test_private_bytes_encrypted_der(self, backend, fmt, password):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: pemfile.read().encode()
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
_skip_if_no_serialization(key, backend)
serialized = key.private_bytes(
serialization.Encoding.DER,
fmt,
serialization.BestAvailableEncryption(password)
)
loaded_key = serialization.load_der_private_key(
serialized, password, backend
)
loaded_priv_num = loaded_key.private_numbers()
priv_num = key.private_numbers()
assert loaded_priv_num == priv_num
@pytest.mark.parametrize(
("encoding", "fmt", "loader_func"),
[
[
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.load_pem_private_key
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.load_der_private_key
],
[
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.load_pem_private_key
],
[
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.load_der_private_key
],
]
)
def test_private_bytes_unencrypted(self, backend, encoding, fmt,
loader_func):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: pemfile.read().encode()
)
key = serialization.load_pem_private_key(key_bytes, None, backend)
_skip_if_no_serialization(key, backend)
serialized = key.private_bytes(
encoding, fmt, serialization.NoEncryption()
)
loaded_key = loader_func(serialized, None, backend)
loaded_priv_num = loaded_key.private_numbers()
priv_num = key.private_numbers()
assert loaded_priv_num == priv_num
@pytest.mark.parametrize(
("key_path", "encoding", "loader_func"),
[
[
os.path.join(
"asymmetric", "PEM_Serialization", "ec_private_key.pem"
),
serialization.Encoding.PEM,
serialization.load_pem_private_key
],
[
os.path.join(
"asymmetric", "DER_Serialization", "ec_private_key.der"
),
serialization.Encoding.DER,
serialization.load_der_private_key
],
]
)
def test_private_bytes_traditional_openssl_unencrypted(
self, backend, key_path, encoding, loader_func
):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
key_path, lambda pemfile: pemfile.read(), mode="rb"
)
key = loader_func(key_bytes, None, backend)
serialized = key.private_bytes(
encoding,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption()
)
assert serialized == key_bytes
def test_private_bytes_traditional_der_encrypted_invalid(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.BestAvailableEncryption(b"password")
)
def test_private_bytes_invalid_encoding(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(TypeError):
key.private_bytes(
"notencoding",
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()
)
def test_private_bytes_invalid_format(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
"invalidformat",
serialization.NoEncryption()
)
def test_private_bytes_invalid_encryption_algorithm(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
"notanencalg"
)
def test_private_bytes_unsupported_encryption_type(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read().encode(), None, backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
DummyKeyEncryption()
)
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
@pytest.mark.requires_backend_interface(interface=PEMSerializationBackend)
class TestEllipticCurvePEMPublicKeySerialization(object):
@pytest.mark.parametrize(
("key_path", "loader_func", "encoding"),
[
(
os.path.join(
"asymmetric", "PEM_Serialization", "ec_public_key.pem"
),
serialization.load_pem_public_key,
serialization.Encoding.PEM,
), (
os.path.join(
"asymmetric", "DER_Serialization", "ec_public_key.der"
),
serialization.load_der_public_key,
serialization.Encoding.DER,
)
]
)
def test_public_bytes_match(self, key_path, loader_func, encoding,
backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
key_path, lambda pemfile: pemfile.read(), mode="rb"
)
key = loader_func(key_bytes, backend)
_skip_if_no_serialization(key, backend)
serialized = key.public_bytes(
encoding, serialization.PublicFormat.SubjectPublicKeyInfo,
)
assert serialized == key_bytes
def test_public_bytes_invalid_encoding(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PEM_Serialization", "ec_public_key.pem"
),
lambda pemfile: serialization.load_pem_public_key(
pemfile.read().encode(), backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(TypeError):
key.public_bytes(
"notencoding",
serialization.PublicFormat.SubjectPublicKeyInfo
)
def test_public_bytes_invalid_format(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PEM_Serialization", "ec_public_key.pem"
),
lambda pemfile: serialization.load_pem_public_key(
pemfile.read().encode(), backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(TypeError):
key.public_bytes(serialization.Encoding.PEM, "invalidformat")
def test_public_bytes_pkcs1_unsupported(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key = load_vectors_from_file(
os.path.join(
"asymmetric", "PEM_Serialization", "ec_public_key.pem"
),
lambda pemfile: serialization.load_pem_public_key(
pemfile.read().encode(), backend
)
)
_skip_if_no_serialization(key, backend)
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.PKCS1
)