sm3.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. require __DIR__ . '/../vendor/autoload.php';
  3. function eq($a, $b)
  4. {
  5. if ($a !== $b) {
  6. print_r([$a, '!==', $b]);
  7. throw new \Exception('error');
  8. }
  9. print_r([$a, $b, 'true']);
  10. }
  11. function hmac($data = null, $secret = null, $raw_output = false)
  12. {
  13. $sm3 = new \OneSm\Sm3();
  14. $size = \strlen($sm3->sign('test'));
  15. $pack = 'H' . (string)$size;
  16. if (\strlen($secret) > $size) {
  17. $secret = pack($pack, $sm3->sign($secret));
  18. }
  19. $key = str_pad($secret, $size, \chr(0x00));
  20. $ipad = $key ^ str_repeat(\chr(0x36), $size);
  21. $opad = $key ^ str_repeat(\chr(0x5C), $size);
  22. $hmac = $sm3->sign($opad . pack($pack, $sm3->sign($ipad . $data)));
  23. return $raw_output ? pack($pack, $hmac) : $hmac;
  24. }
  25. $sm3 = new \OneSm\Sm3();
  26. eq('66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0', $sm3->sign('abc'));
  27. eq('1294da78431a20991584c68a669f2c59618e08bf0d7989f35f6ae1d7d570e143', $sm3->sign(str_repeat("adfas哈哈哈", 100)));
  28. eq('1ab21d8355cfa17f8e61194831e81a8f22bec8c728fefb747ed035eb5082aa2b', $sm3->sign(''));
  29. eq(
  30. '8e4bd77d8a10526fae772bb6014dfaed0335491e1cdfa92d3aca1481ae5d9a83',
  31. hmac(str_repeat('abc', 1000), 'secret')
  32. );
  33. eq(
  34. hex2bin('8e4bd77d8a10526fae772bb6014dfaed0335491e1cdfa92d3aca1481ae5d9a83'),
  35. hmac(str_repeat('abc', 1000), 'secret', true)
  36. );