XOR.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * xor.c : Source for the trivial cipher which XORs the message with the key.
  3. * The key can be up to 32 bytes long.
  4. *
  5. * Part of the Python Cryptography Toolkit
  6. *
  7. * Contributed by Barry Warsaw and others.
  8. *
  9. * =======================================================================
  10. * The contents of this file are dedicated to the public domain. To the
  11. * extent that dedication to the public domain is not available, everyone
  12. * is granted a worldwide, perpetual, royalty-free, non-exclusive license
  13. * to exercise all rights associated with the contents of this file for
  14. * any purpose whatsoever. No rights are reserved.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  20. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. * =======================================================================
  25. */
  26. #include "Python.h"
  27. #define MODULE_NAME _XOR
  28. #define BLOCK_SIZE 1
  29. #define KEY_SIZE 0
  30. #define MAX_KEY_SIZE 32
  31. typedef struct
  32. {
  33. unsigned char key[MAX_KEY_SIZE];
  34. int keylen, last_pos;
  35. } stream_state;
  36. static void
  37. stream_init(stream_state *self, unsigned char *key, int len)
  38. {
  39. int i;
  40. if (len > MAX_KEY_SIZE)
  41. {
  42. PyErr_Format(PyExc_ValueError,
  43. "XOR key must be no longer than %d bytes",
  44. MAX_KEY_SIZE);
  45. return;
  46. }
  47. self->keylen = len;
  48. self->last_pos = 0;
  49. for(i=0; i<len; i++)
  50. {
  51. self->key[i] = key[i];
  52. }
  53. }
  54. /* Encryption and decryption are symmetric */
  55. #define stream_decrypt stream_encrypt
  56. static void stream_encrypt(stream_state *self, unsigned char *block,
  57. int len)
  58. {
  59. int i, j = self->last_pos;
  60. for(i=0; i<len; i++, j=(j+1) % self->keylen)
  61. {
  62. block[i] ^= self->key[j];
  63. }
  64. self->last_pos = j;
  65. }
  66. #include "stream_template.c"