utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import typing
  5. from cryptography import utils
  6. from cryptography.hazmat._der import (
  7. DERReader,
  8. INTEGER,
  9. SEQUENCE,
  10. encode_der,
  11. encode_der_integer,
  12. )
  13. from cryptography.hazmat.primitives import hashes
  14. def decode_dss_signature(signature: bytes) -> typing.Tuple[int, int]:
  15. with DERReader(signature).read_single_element(SEQUENCE) as seq:
  16. r = seq.read_element(INTEGER).as_integer()
  17. s = seq.read_element(INTEGER).as_integer()
  18. return r, s
  19. def encode_dss_signature(r: int, s: int) -> bytes:
  20. return encode_der(
  21. SEQUENCE,
  22. encode_der(INTEGER, encode_der_integer(r)),
  23. encode_der(INTEGER, encode_der_integer(s)),
  24. )
  25. class Prehashed(object):
  26. def __init__(self, algorithm: hashes.HashAlgorithm):
  27. if not isinstance(algorithm, hashes.HashAlgorithm):
  28. raise TypeError("Expected instance of HashAlgorithm.")
  29. self._algorithm = algorithm
  30. self._digest_size = algorithm.digest_size
  31. digest_size = utils.read_only_property("_digest_size")