sm4_cbc_mactest.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the License); you may
  5. * not use this file except in compliance with the License.
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. */
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <assert.h>
  13. #include <gmssl/mem.h>
  14. #include <gmssl/rand.h>
  15. #include <gmssl/error.h>
  16. #include <gmssl/sm4_cbc_mac.h>
  17. static int test_sm4_cbc_mac(void)
  18. {
  19. SM4_KEY sm4_key;
  20. SM4_CBC_MAC_CTX ctx;
  21. uint8_t key[16];
  22. uint8_t iv[16] = {0};
  23. uint8_t m[128];
  24. uint8_t c[128];
  25. uint8_t mac1[16];
  26. uint8_t mac2[16];
  27. uint8_t *p;
  28. size_t len, left;
  29. rand_bytes(key, sizeof(key));
  30. rand_bytes(m, sizeof(m));
  31. sm4_set_encrypt_key(&sm4_key, key);
  32. // test 1
  33. sm4_cbc_encrypt(&sm4_key, iv, m, sizeof(m)/16, c);
  34. memcpy(mac1, c + sizeof(m) - 16, 16);
  35. sm4_cbc_mac_init(&ctx, key);
  36. p = m;
  37. len = 0;
  38. left = sizeof(m);
  39. while (left) {
  40. len = left < len ? left : len;
  41. sm4_cbc_mac_update(&ctx, p, len);
  42. p += len;
  43. left -= len;
  44. len++;
  45. }
  46. sm4_cbc_mac_finish(&ctx, mac2);
  47. if (memcmp(mac1, mac2, 16)) {
  48. error_print();
  49. return -1;
  50. }
  51. // test 2
  52. m[sizeof(m) - 1] = 0;
  53. sm4_cbc_encrypt(&sm4_key, iv, m, sizeof(m)/16, c);
  54. memcpy(mac1, c + sizeof(m) - 16, 16);
  55. sm4_cbc_mac_init(&ctx, key);
  56. p = m;
  57. len = 0;
  58. left = sizeof(m) - 1;
  59. while (left) {
  60. len = left < len ? left : len;
  61. sm4_cbc_mac_update(&ctx, p, len);
  62. p += len;
  63. left -= len;
  64. len++;
  65. }
  66. sm4_cbc_mac_finish(&ctx, mac2);
  67. if (memcmp(mac1, mac2, 16)) {
  68. error_print();
  69. return -1;
  70. }
  71. printf("%s() ok\n", __FUNCTION__);
  72. return 1;
  73. }
  74. int main(void)
  75. {
  76. if (test_sm4_cbc_mac() != 1) { error_print(); return -1; }
  77. return 0;
  78. }