Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from __future__ import annotations
  2. import base64
  3. import hashlib
  4. import secrets
  5. import sys
  6. __all__ = ["accept_key", "apply_mask"]
  7. GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  8. def generate_key() -> str:
  9. """
  10. Generate a random key for the Sec-WebSocket-Key header.
  11. """
  12. key = secrets.token_bytes(16)
  13. return base64.b64encode(key).decode()
  14. def accept_key(key: str) -> str:
  15. """
  16. Compute the value of the Sec-WebSocket-Accept header.
  17. Args:
  18. key: value of the Sec-WebSocket-Key header.
  19. """
  20. sha1 = hashlib.sha1((key + GUID).encode()).digest()
  21. return base64.b64encode(sha1).decode()
  22. def apply_mask(data: bytes, mask: bytes) -> bytes:
  23. """
  24. Apply masking to the data of a WebSocket message.
  25. Args:
  26. data: data to mask.
  27. mask: 4-bytes mask.
  28. """
  29. if len(mask) != 4:
  30. raise ValueError("mask must contain 4 bytes")
  31. data_int = int.from_bytes(data, sys.byteorder)
  32. mask_repeated = mask * (len(data) // 4) + mask[: len(data) % 4]
  33. mask_int = int.from_bytes(mask_repeated, sys.byteorder)
  34. return (data_int ^ mask_int).to_bytes(len(data), sys.byteorder)