strxor.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, c_size_t,
  31. create_string_buffer, get_raw_buffer,
  32. c_uint8_ptr, is_writeable_buffer)
  33. _raw_strxor = load_pycryptodome_raw_lib("Cryptodome.Util._strxor",
  34. """
  35. void strxor(const uint8_t *in1,
  36. const uint8_t *in2,
  37. uint8_t *out, size_t len);
  38. void strxor_c(const uint8_t *in,
  39. uint8_t c,
  40. uint8_t *out,
  41. size_t len);
  42. """)
  43. def strxor(term1, term2, output=None):
  44. """XOR two byte strings.
  45. Args:
  46. term1 (bytes/bytearray/memoryview):
  47. The first term of the XOR operation.
  48. term2 (bytes/bytearray/memoryview):
  49. The second term of the XOR operation.
  50. output (bytearray/memoryview):
  51. The location where the result must be written to.
  52. If ``None``, the result is returned.
  53. :Return:
  54. If ``output`` is ``None``, a new ``bytes`` string with the result.
  55. Otherwise ``None``.
  56. """
  57. if len(term1) != len(term2):
  58. raise ValueError("Only byte strings of equal length can be xored")
  59. if output is None:
  60. result = create_string_buffer(len(term1))
  61. else:
  62. # Note: output may overlap with either input
  63. result = output
  64. if not is_writeable_buffer(output):
  65. raise TypeError("output must be a bytearray or a writeable memoryview")
  66. if len(term1) != len(output):
  67. raise ValueError("output must have the same length as the input"
  68. " (%d bytes)" % len(term1))
  69. _raw_strxor.strxor(c_uint8_ptr(term1),
  70. c_uint8_ptr(term2),
  71. c_uint8_ptr(result),
  72. c_size_t(len(term1)))
  73. if output is None:
  74. return get_raw_buffer(result)
  75. else:
  76. return None
  77. def strxor_c(term, c, output=None):
  78. """XOR a byte string with a repeated sequence of characters.
  79. Args:
  80. term(bytes/bytearray/memoryview):
  81. The first term of the XOR operation.
  82. c (bytes):
  83. The byte that makes up the second term of the XOR operation.
  84. output (None or bytearray/memoryview):
  85. If not ``None``, the location where the result is stored into.
  86. Return:
  87. If ``output`` is ``None``, a new ``bytes`` string with the result.
  88. Otherwise ``None``.
  89. """
  90. if not 0 <= c < 256:
  91. raise ValueError("c must be in range(256)")
  92. if output is None:
  93. result = create_string_buffer(len(term))
  94. else:
  95. # Note: output may overlap with either input
  96. result = output
  97. if not is_writeable_buffer(output):
  98. raise TypeError("output must be a bytearray or a writeable memoryview")
  99. if len(term) != len(output):
  100. raise ValueError("output must have the same length as the input"
  101. " (%d bytes)" % len(term))
  102. _raw_strxor.strxor_c(c_uint8_ptr(term),
  103. c,
  104. c_uint8_ptr(result),
  105. c_size_t(len(term))
  106. )
  107. if output is None:
  108. return get_raw_buffer(result)
  109. else:
  110. return None
  111. def _strxor_direct(term1, term2, result):
  112. """Very fast XOR - check conditions!"""
  113. _raw_strxor.strxor(term1, term2, result, c_size_t(len(term1)))