omac_init.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  2. *
  3. * LibTomCrypt is a library that provides various cryptographic
  4. * algorithms in a highly modular and flexible manner.
  5. *
  6. * The library is free for all purposes without any express
  7. * guarantee it works.
  8. *
  9. * Tom St Denis, [email protected], http://libtomcrypt.org
  10. */
  11. /* OMAC1 Support by Tom St Denis (for 64 and 128 bit block ciphers only) */
  12. #include "mycrypt.h"
  13. #ifdef OMAC
  14. int omac_init(omac_state *omac, int cipher, const unsigned char *key, unsigned long keylen)
  15. {
  16. int err, x, y, mask, msb, len;
  17. _ARGCHK(omac != NULL);
  18. _ARGCHK(key != NULL);
  19. /* schedule the key */
  20. if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
  21. return err;
  22. }
  23. /* now setup the system */
  24. switch (cipher_descriptor[cipher].block_length) {
  25. case 8: mask = 0x1B;
  26. len = 8;
  27. break;
  28. case 16: mask = 0x87;
  29. len = 16;
  30. break;
  31. default: return CRYPT_INVALID_ARG;
  32. }
  33. if ((err = cipher_descriptor[cipher].setup(key, keylen, 0, &omac->key)) != CRYPT_OK) {
  34. return err;
  35. }
  36. /* ok now we need Lu and Lu^2 [calc one from the other] */
  37. /* first calc L which is Ek(0) */
  38. zeromem(omac->Lu[0], cipher_descriptor[cipher].block_length);
  39. cipher_descriptor[cipher].ecb_encrypt(omac->Lu[0], omac->Lu[0], &omac->key);
  40. /* now do the mults, whoopy! */
  41. for (x = 0; x < 2; x++) {
  42. /* if msb(L * u^(x+1)) = 0 then just shift, otherwise shift and xor constant mask */
  43. msb = omac->Lu[x][0] >> 7;
  44. /* shift left */
  45. for (y = 0; y < (len - 1); y++) {
  46. omac->Lu[x][y] = ((omac->Lu[x][y] << 1) | (omac->Lu[x][y+1] >> 7)) & 255;
  47. }
  48. omac->Lu[x][len - 1] = ((omac->Lu[x][len - 1] << 1) ^ (msb ? mask : 0)) & 255;
  49. /* copy up as require */
  50. if (x == 0) {
  51. XMEMCPY(omac->Lu[1], omac->Lu[0], sizeof(omac->Lu[0]));
  52. }
  53. }
  54. /* setup state */
  55. omac->cipher_idx = cipher;
  56. omac->buflen = 0;
  57. omac->blklen = len;
  58. zeromem(omac->prev, sizeof(omac->prev));
  59. zeromem(omac->block, sizeof(omac->block));
  60. return CRYPT_OK;
  61. }
  62. #endif