Adding a simple MAC to url parameters?

2019-08-02 07:50发布

问题:

I want to add a simple kind of MAC to some of my URL parameters. This is only intended as an additional line of defense against application bugs and caching related problems/bugs, and not intended as any form of replacement of the actual login security in the application. A given business-object-id is already protected by backends to be limited to a single user.

So basically I'd like to add a short authentication code to my url parameters, on the size of 2-4 characters. I think I'd like to have a reversible function along the lines of f(business-data-id + logged-on-user-id + ??) = hash, but I am open to suggestions.

The primary intention is to stop id guessing, and to make sure that url's are fairly distinct per logged on user. I also don't want something big and clunky like an MD5.

回答1:

Since you aren't looking for cryptographic quality, maybe a 24-bit CRC would fit your needs. While MD5 is "fast" in absolute terms, CRC is, relatively, "blindingly fast". Then the 3-byte CRC could be text-encoded into four characters with Base-64 encoding.

Here's a Java implementation of the check used for OpenPGP ASCII-armor checksums:

private static byte[] crc(byte[] data)
{
  int crc = 0xB704CE;
  for (int octets = 0; octets < data.length; ++octets) {
    crc ^= (data[octets] & 0xFF) << 16;
    for (int i = 0; i < 8; ++i) {
      crc <<= 1;
      if ((crc & 0x1000000) != 0)
        crc ^= 0x1864CFB;
    }
  }
  byte[] b = new byte[3];
  for (int shift = 16, idx = 0; shift >= 0; shift -= 8) {
    b[idx++] = (byte) (crc >>> shift);
  }
  return b;
}

I would hash a secret key (which is known only by the server), together with whatever you want to protect—probably the combination of object identifier and user identifier.



回答2:

If what you want is basically MD5 but smaller, why not just use MD5 but just the last 4 characters? This doesn't add a huge blob to your urls, it's always 4 nice hex digits.



回答3:

A quick question for which I'm sure there's a good answer for, but why not store this information in a cookie?

Then you could use something big and clunky like MD5 and your URLs would still be pretty.