Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <cstdint>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <cstdlib>
  5.  
  6. namespace crc32
  7. {
  8.   void generate_table(uint32_t(&table)[256])
  9.   {
  10.     for (uint32_t i = 0; i < 256; i++)
  11.     {
  12.       auto c = i;
  13.       for (size_t j = 0; j < 8; j++)
  14.         if (c & 1)
  15.           c = 0xEDB88320 ^ (c >> 1);
  16.         else
  17.           c >>= 1;
  18.       table[i] = c;
  19.     }
  20.   }
  21.  
  22.   static uint32_t update(uint32_t(&table)[256], uint32_t initial, const void* buf, size_t len)
  23.   {
  24.     auto c = initial ^ 0xFFFFFFFF;
  25.     const auto* u = static_cast<const uint8_t*>(buf);
  26.     for (size_t i = 0; i < len; ++i)
  27.     {
  28.       c = table[(c ^ u[i]) & 0xFF] ^ (c >> 8);
  29.     }
  30.     return c ^ 0xFFFFFFFF;
  31.   }
  32. };
  33.  
  34. int main(int argc, char** argv)
  35. {
  36.   const auto fp = fopen(argv[1], "rb");
  37.   fseek(fp, 0, SEEK_END);
  38.   const auto sz = ftell(fp);
  39.   rewind(fp);
  40.   const auto png = new std::uint8_t[sz];
  41.   fread(png, 1, sz, fp);
  42.   fclose(fp);
  43.   auto it = png + sz - 4;
  44.   while (*(uint32_t*)it != 'DNEI')
  45.     --it;
  46.   const auto new_sz = atoll(argv[3]);
  47.   const auto new_png = new std::uint8_t[new_sz];
  48.   memset(new_png, 'a', new_sz);
  49.   memcpy(new_png, png, it - png);
  50.   auto inv = (uint32_t*)(it - png + new_png);
  51.   *inv++ = new_sz - sz - 12;
  52.   *inv++ = 'iTXt';
  53.   const auto start = inv;
  54.   (uint8_t*&)inv += new_sz - sz - 12;
  55.   uint32_t table[256];
  56.   crc32::generate_table(table);
  57.   *inv = crc32::update(table, 0, start, (char*)inv - (char*)start);
  58.   memcpy(new_png + new_sz - (png + sz - it), it, png + sz - it);
  59.   const auto ofp = fopen(argv[2], "wb");
  60.   fwrite(new_png, new_sz, 1, ofp);
  61.   fclose(fp);
  62.   delete[] png;
  63.   delete[] new_png;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement