strxor.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 Crypto.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(
  34. "Crypto.Util._strxor",
  35. """
  36. void strxor(const uint8_t *in1,
  37. const uint8_t *in2,
  38. uint8_t *out, size_t len);
  39. void strxor_c(const uint8_t *in,
  40. uint8_t c,
  41. uint8_t *out,
  42. size_t len);
  43. """)
  44. def strxor(term1, term2, output=None):
  45. """From two byte strings of equal length,
  46. create a third one which is the byte-by-byte XOR of the two.
  47. Args:
  48. term1 (bytes/bytearray/memoryview):
  49. The first byte string to XOR.
  50. term2 (bytes/bytearray/memoryview):
  51. The second byte string to XOR.
  52. output (bytearray/memoryview):
  53. The location where the result will be written to.
  54. It must have the same length as ``term1`` and ``term2``.
  55. If ``None``, the result is returned.
  56. :Return:
  57. If ``output`` is ``None``, a new byte string with the result.
  58. Otherwise ``None``.
  59. .. note::
  60. ``term1`` and ``term2`` must have the same length.
  61. """
  62. if len(term1) != len(term2):
  63. raise ValueError("Only byte strings of equal length can be xored")
  64. if output is None:
  65. result = create_string_buffer(len(term1))
  66. else:
  67. # Note: output may overlap with either input
  68. result = output
  69. if not is_writeable_buffer(output):
  70. raise TypeError("output must be a bytearray or a writeable memoryview")
  71. if len(term1) != len(output):
  72. raise ValueError("output must have the same length as the input"
  73. " (%d bytes)" % len(term1))
  74. _raw_strxor.strxor(c_uint8_ptr(term1),
  75. c_uint8_ptr(term2),
  76. c_uint8_ptr(result),
  77. c_size_t(len(term1)))
  78. if output is None:
  79. return get_raw_buffer(result)
  80. else:
  81. return None
  82. def strxor_c(term, c, output=None):
  83. """From a byte string, create a second one of equal length
  84. where each byte is XOR-red with the same value.
  85. Args:
  86. term(bytes/bytearray/memoryview):
  87. The byte string to XOR.
  88. c (int):
  89. Every byte in the string will be XOR-ed with this value.
  90. It must be between 0 and 255 (included).
  91. output (None or bytearray/memoryview):
  92. The location where the result will be written to.
  93. It must have the same length as ``term``.
  94. If ``None``, the result is returned.
  95. Return:
  96. If ``output`` is ``None``, a new ``bytes`` string with the result.
  97. Otherwise ``None``.
  98. """
  99. if not 0 <= c < 256:
  100. raise ValueError("c must be in range(256)")
  101. if output is None:
  102. result = create_string_buffer(len(term))
  103. else:
  104. # Note: output may overlap with either input
  105. result = output
  106. if not is_writeable_buffer(output):
  107. raise TypeError("output must be a bytearray or a writeable memoryview")
  108. if len(term) != len(output):
  109. raise ValueError("output must have the same length as the input"
  110. " (%d bytes)" % len(term))
  111. _raw_strxor.strxor_c(c_uint8_ptr(term),
  112. c,
  113. c_uint8_ptr(result),
  114. c_size_t(len(term))
  115. )
  116. if output is None:
  117. return get_raw_buffer(result)
  118. else:
  119. return None
  120. def _strxor_direct(term1, term2, result):
  121. """Very fast XOR - check conditions!"""
  122. _raw_strxor.strxor(term1, term2, result, c_size_t(len(term1)))