39 lines
1.9 KiB
Python
39 lines
1.9 KiB
Python
import copy
|
|
import time
|
|
|
|
import pytest
|
|
from cryptography.exceptions import InvalidSignature, InvalidTag
|
|
from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
|
|
from cryptography.hazmat.primitives import serialization
|
|
from relay.crypto import (issue_ca, issue_device, raw_public, seal, open_envelope, verify_device)
|
|
|
|
|
|
def test_encrypted_and_authenticated():
|
|
signer = ed25519.Ed25519PrivateKey.generate()
|
|
recipient = x25519.X25519PrivateKey.generate()
|
|
envelope = seal({"text": "秘密合同"}, raw_public(recipient.public_key()), signer, host_id="host", session_id="session")
|
|
assert "秘密" not in str(envelope)
|
|
assert open_envelope(envelope, recipient, signer.public_key(), host_id="host", session_id="session")["text"] == "秘密合同"
|
|
damaged = copy.deepcopy(envelope)
|
|
damaged["ciphertext"] = damaged["ciphertext"][:-4] + "AAAA"
|
|
with pytest.raises(InvalidSignature):
|
|
open_envelope(damaged, recipient, signer.public_key(), host_id="host", session_id="session")
|
|
with pytest.raises(ValueError):
|
|
open_envelope(envelope, recipient, signer.public_key(), host_id="other", session_id="session")
|
|
# Long-term signing key alone cannot recover a recorded session's data.
|
|
with pytest.raises(InvalidTag):
|
|
open_envelope(envelope, x25519.X25519PrivateKey.generate(), signer.public_key(), host_id="host", session_id="session")
|
|
|
|
|
|
def test_certificate_identity_and_trust():
|
|
ca_key, ca = issue_ca()
|
|
device = ed25519.Ed25519PrivateKey.generate()
|
|
pem = issue_device(ca_key, ca, "a" * 32, device.public_key()).public_bytes(serialization.Encoding.PEM).decode()
|
|
ca_pem = ca.public_bytes(serialization.Encoding.PEM)
|
|
verify_device(pem, ca_pem, "a" * 32)
|
|
with pytest.raises(ValueError):
|
|
verify_device(pem, ca_pem, "b" * 32)
|
|
_, other_ca = issue_ca()
|
|
with pytest.raises((ValueError, InvalidSignature)):
|
|
verify_device(pem, other_ca.public_bytes(serialization.Encoding.PEM), "a" * 32)
|