How to accept md5sum via command line in C?

typedef union
{
    uint ui[4];
} md5hash;

void main(void)
{
    int opt;

    while ((opt = getopt(argc, argv, "c:t:s:h:")) != -1) {
        switch (opt) {
        case 'h':
            hash = optarg;
            break;
        default: /* '?' */
            exit(EXIT_FAILURE);
        }
    }

    md5hash hash;

    sscanf(hash, "%x%x%x%x", &hash.ui);
}

      

./program -h ffffffffffffffffffffffffffffffff

I want to do above, but sscanf is not accepting md5sum correctly ...

+1


source to share


2 answers


  1. You seem to have two variables called hash, except that one of them is implicit in your code.
  2. The operator sscanf

    tries to read hash

    back into itself, but obviously it won't find the hex digits.
  3. %x

    can load a different sized integer in hex on different platforms because you didn't specify any specific read length for each field.
  4. You are not considering the finiteness of the machine.

If you have a hex string, say in hashString

, then you can probably try



int fieldsScanned = sscanf (hashString, "%8x%8x%8x%8x", &hash.ui[0], &hash.ui[1], &hash.ui[2], &hash.ui[3]);

if (fieldsScanned == 4)
{
    // MD5 sum is in hash variable.
}

      

+5


source


int
parse_hex(char *s, unsigned char *hex, int len)
{
  int i, r = 0;

  len *= 2;
  for (i = 0; ; i++, s++)
    {
      if (*s == 0 && !(i & 1))
        return i / 2;
      if (i == len)
        {
          fprintf(stderr, "parsehex: string too long\n");
          //exit(1);
        }
      if (*s >= '0' && *s <= '9')
        r = (r << 4) | (*s - '0');
      else if (*s >= 'a' && *s <= 'f')
        r = (r << 4) | (*s - ('a' - 10));
      else if (*s >= 'A' && *s <= 'F')
        r = (r << 4) | (*s - ('a' - 10));
      else
        {
          fprintf(stderr, "parsehex: bad string\n");
          //exit(1);
        }
      if ((i & 1) != 0)
        {
          hex[i / 2] = r;
          r = 0;
        }
    }
}

void
parse_md5(char *s, unsigned char *md5)
{
  if (!*s)
    {
      memset(md5, 0, 16);
      return;
    }
  if (parse_hex(s, md5, 16) != 16)
    {
      fprintf(stderr, "parsemd5: bad md5\n");
      //exit(1);
    }
}

      



in fact, the sscanf () method above does not work, it reads bytes in reverse order in double words.

0


source







All Articles