crypto1.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "crypto1.h"
  2. #include "nfc_util.h"
  3. #include <furi.h>
  4. // Algorithm from https://github.com/RfidResearchGroup/proxmark3.git
  5. #define SWAPENDIAN(x) (x = (x >> 8 & 0xff00ff) | (x & 0xff00ff) << 8, x = x >> 16 | x << 16)
  6. #define LF_POLY_ODD (0x29CE5C)
  7. #define LF_POLY_EVEN (0x870804)
  8. #define BEBIT(x, n) FURI_BIT(x, (n) ^ 24)
  9. void crypto1_reset(Crypto1* crypto1) {
  10. furi_assert(crypto1);
  11. crypto1->even = 0;
  12. crypto1->odd = 0;
  13. }
  14. void crypto1_init(Crypto1* crypto1, uint64_t key) {
  15. furi_assert(crypto1);
  16. crypto1->even = 0;
  17. crypto1->odd = 0;
  18. for(int8_t i = 47; i > 0; i -= 2) {
  19. crypto1->odd = crypto1->odd << 1 | FURI_BIT(key, (i - 1) ^ 7);
  20. crypto1->even = crypto1->even << 1 | FURI_BIT(key, i ^ 7);
  21. }
  22. }
  23. uint32_t crypto1_filter(uint32_t in) {
  24. uint32_t out = 0;
  25. out = 0xf22c0 >> (in & 0xf) & 16;
  26. out |= 0x6c9c0 >> (in >> 4 & 0xf) & 8;
  27. out |= 0x3c8b0 >> (in >> 8 & 0xf) & 4;
  28. out |= 0x1e458 >> (in >> 12 & 0xf) & 2;
  29. out |= 0x0d938 >> (in >> 16 & 0xf) & 1;
  30. return FURI_BIT(0xEC57E80A, out);
  31. }
  32. uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted) {
  33. furi_assert(crypto1);
  34. uint8_t out = crypto1_filter(crypto1->odd);
  35. uint32_t feed = out & (!!is_encrypted);
  36. feed ^= !!in;
  37. feed ^= LF_POLY_ODD & crypto1->odd;
  38. feed ^= LF_POLY_EVEN & crypto1->even;
  39. crypto1->even = crypto1->even << 1 | (nfc_util_even_parity32(feed));
  40. FURI_SWAP(crypto1->odd, crypto1->even);
  41. return out;
  42. }
  43. uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted) {
  44. furi_assert(crypto1);
  45. uint8_t out = 0;
  46. for(uint8_t i = 0; i < 8; i++) {
  47. out |= crypto1_bit(crypto1, FURI_BIT(in, i), is_encrypted) << i;
  48. }
  49. return out;
  50. }
  51. uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted) {
  52. furi_assert(crypto1);
  53. uint32_t out = 0;
  54. for(uint8_t i = 0; i < 32; i++) {
  55. out |= crypto1_bit(crypto1, BEBIT(in, i), is_encrypted) << (24 ^ i);
  56. }
  57. return out;
  58. }
  59. uint32_t prng_successor(uint32_t x, uint32_t n) {
  60. SWAPENDIAN(x);
  61. while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31;
  62. return SWAPENDIAN(x);
  63. }