简体   繁体   中英

Issues talking between Arduino SHA1-HMAC and base64 encoding and Python

So, what I'm after is a base64-encoded, SHA1 HMAC. I've found the Adafruit Cryptosuite fork which is a stripped-down SHA1 only fork of Cathedrow's library. I want to be able to chat between my Arduino and a Python app, using base64 encoded SHA1-HMAC signatures. However, it doesn't seem to generate consistent results:

On the Arduino, the following should generate the SHA1-HMAC for the string 'testing':

  signingKey[] = "testKey";

  Sha1.initHmac_P((uint8_t *)signingKey, sizeof(signingKey) - 1);
  Sha1.print("testing");

I now want to base64 encode this, which Adafruit's Tweet Example appears to have a tidy function for doing (I realise this expects only a SHA1-HMAC, nothing else):

  // base64-encode SHA-1 hash output.  This is NOT a general-purpose base64
  // encoder!  It's stripped down for the fixed-length hash -- always 20
  // bytes input, always 27 chars output + '='.
  for(in = Sha1.resultHmac(), out=0; ; in += 3) { // octets to sextets
    b64[out++] =   in[0] >> 2;
    b64[out++] = ((in[0] & 0x03) << 4) | (in[1] >> 4);
    if(out >= 26) break;
    b64[out++] = ((in[1] & 0x0f) << 2) | (in[2] >> 6);
    b64[out++] =   in[2] & 0x3f;
  }
  b64[out] = (in[1] & 0x0f) << 2;
  // Remap sextets to base64 ASCII chars
  for(i=0; i<=out; i++) b64[i] = pgm_read_byte(&b64chars[b64[i]]);
  b64[i++] = '=';
  b64[i++] = 0;

Outputs:

qn9vJmo4Q6KhPgbn5nVOSOUCU5Q=

But, all is not well when I look at this from the python side:

hm = hmac.new('testKey', 'testing', hashlib.sha1)
print binascii.b2a_base64(hm.digest())[:-1]

Outputs:

YNQScdQ7h1t5Hi1Uw0vz8Biil2M=

Clearly these two are different. Unfortunately I haven't used Arduino/C++ much and am more familiar with the Python side. Is there an obvious mistake in what I'm trying to do, or are the libraries I'm using inadequate for purpose?

Thanks!

在这里给出答案:正确的函数是Sha1.initHmac ,而不是Sha1.initHmac_P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM