encrypt.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <stdint.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. struct expanded_key {
  5. uint32_t l[16], r[16];
  6. };
  7. void __des_setkey(const unsigned char *key, struct expanded_key *ekey);
  8. void __do_des(uint32_t l_in, uint32_t r_in,
  9. uint32_t *l_out, uint32_t *r_out,
  10. uint32_t count, uint32_t saltbits, const struct expanded_key *ekey);
  11. static struct expanded_key __encrypt_key;
  12. void setkey(const char *key)
  13. {
  14. unsigned char bkey[8];
  15. int i, j;
  16. for (i = 0; i < 8; i++) {
  17. bkey[i] = 0;
  18. for (j = 7; j >= 0; j--, key++)
  19. bkey[i] |= (uint32_t)(*key & 1) << j;
  20. }
  21. __des_setkey(bkey, &__encrypt_key);
  22. }
  23. void encrypt(char *block, int edflag)
  24. {
  25. struct expanded_key decrypt_key, *key;
  26. uint32_t b[2];
  27. int i, j;
  28. char *p;
  29. p = block;
  30. for (i = 0; i < 2; i++) {
  31. b[i] = 0;
  32. for (j = 31; j >= 0; j--, p++)
  33. b[i] |= (uint32_t)(*p & 1) << j;
  34. }
  35. key = &__encrypt_key;
  36. if (edflag) {
  37. key = &decrypt_key;
  38. for (i = 0; i < 16; i++) {
  39. decrypt_key.l[i] = __encrypt_key.l[15-i];
  40. decrypt_key.r[i] = __encrypt_key.r[15-i];
  41. }
  42. }
  43. __do_des(b[0], b[1], b, b + 1, 1, 0, key);
  44. p = block;
  45. for (i = 0; i < 2; i++)
  46. for (j = 31; j >= 0; j--)
  47. *p++ = b[i]>>j & 1;
  48. }